Posts Tagged ‘EventHandler’

While working on my WPF PowerShell console, I’m working on implementing PSRawUserInterface, and had to implement a method called ReadKey which returns a KeyInfo object. KeyInfo is a pretty simple struct class with four properties:

  • VirtualKeyCode
  • Character
  • ControlKeyState
  • KeyDown

So it doesn’t seem like it would be a real problem … just handle the KeyDown event or PreviewKeyDown event on the WPF control, right? Well, no. Because all of these just use a KeyEventArgs parameter which has a Key property which doesn’t map to a virtual key code (why isn’t the WPF Key enumeration in the right order? It’s ridiculous), and there’s no character information at all.

Thankfully, it is possible to get this information using PInvoke, but I wouldn’t want to try to do this in Silverlight. ;)

Here’s how it goes:

First, you need to get the VirtualKey code. Thankfully, there’s a simple class called KeyInterop, which exposes a static method VirtualKeyFromKey that gets us this information.

Then, we need to get the character. This is much trickier. First we have to get the keyboard state and then we have to map that VirtualKey we got in the first step to a ScanCode, and finally, convert all of that to Unicode, because .Net doesn’t really speak ASCII ;)

The rest of the code is pretty clear, I hope… Read the rest of this entry »

Oisin (x0n) Grehan wrote a module for PowerShell 2 which uses the WMI ManagementEventWatcher and the new event-handling features of PowerShell 2.0 to automatically run scripts whenever you plug in or unplug a removable drive …. specifically, the AutoMount module runs New-PSDrive whenever you plug in a removable, and Remove-PSDrive when you unplug it.

The bottom line is it works great (at least on Vista), and I think I’ll add it to my “AutoModules” ;) ... sadly, it’s not on PoshCode yet :/ but you should go- check it out, it’s a great example of how to work with events in PowerShell, both consuming and creating them (incidentally, x0n’s PSEventing snapin would let you accomplish this in PowerShell v1). [new] x0n’s posted it on PoshCode, so you can Get-PoshCode 525 if you have the module or script installed, or download it from the embed link below:

Search My Content