Tuesday, April 12, 2016

I struggled how to understand how to type into a particular window in PowerShell today and yesterday.

Add-Type @"
   using System;
   using System.Runtime.InteropServices;
   public class UserWindows {
      [DllImport("user32.dll")]
      public static extern IntPtr GetForegroundWindow();
}
"@
$ActiveHandle = [UserWindows]::GetForegroundWindow()
$Process = Get-Process | ? {$_.MainWindowHandle -eq $activeHandle}
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("hello there")

 
 

This does find the process and then put "hello there" to the console, but if you spawned a new explorer window between the third to last line and the second to last line the typing would happen at the new window and not the console. The same is true if it's jammed between the fourth to last and third to last lines of code above. Nuts. There must be some way to tab back to where you were, but I can't figure it out. Some links I found in learning this are:

 
 

The last link above has a list of variables for special keys. I wished there was a way to emulate pressing the Windows key so that I might do things like mimic a Windows key and Left Arrow combination to make an explorer window snap to and fill the left side of the monitor, but there is not. AutoIt might be the thing to use for that. Also Add-Type -AssemblyName System.Windows.Forms is maybe something that could go in the place of [void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms") above.

Attachments: Text version of this message. (2KB)

No comments:

Post a Comment