9

Basically I want to simulate in code a user clicking on the windows key. I know there is SendKeys which allows me to send key presses to windows if I get a handle to them, but what I can't figure out is what I need to get a handle on in order to send Windows key commands. E.g. Windows key + L. Having read into this a bit it appears that CTRL-ESC should pop up the Start Menu also but not sure how to tell it to send the keys to Windows (if this is even possible). Any help would be much appreciated.

Cheers!

mklement0
  • 382,024
  • 64
  • 607
  • 775
PentaPenguin
  • 196
  • 2
  • 11

4 Answers4

9

I don't think you can do this using SendKeys, you will need to p/invoke to an API function instead, probably keybd_event to send either CTRL+ESC or the Windows key.

Here is an example of opening the start menu this way in VB and here is keybd_event with its C# signature on pinvoke.net.

Dale
  • 12,884
  • 8
  • 53
  • 83
5

Some of the things that a user would do via a WinKey shortcut can be done programmatically in other ways. To take your WinKey+L example, you could instead just use the following statement:

Process.Start("rundll32.exe", "user32.dll,LockWorkStation");

If you could elaborate on what exactly you're trying to accomplish, maybe there's a better way than keybd_event (as Dale has suggested).

Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93
  • in your statement above, is it possible to lock a specific user if you are in a netwrok of three pcs for example? – wam090 Jun 13 '14 at 09:17
0

I've used the class provided here by user703016 and worked fine!

for ref:

using System.Runtime.InteropServices;
using System.Windows.Forms;

static class KeyboardSend
{
    [DllImport("user32.dll")]
    private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

    private const int KEYEVENTF_EXTENDEDKEY = 1;
    private const int KEYEVENTF_KEYUP = 2;

    public static void KeyDown(Keys vKey)
    {
        keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0);
    }

    public static void KeyUp(Keys vKey)
    {
        keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    }
}

used in this way:

KeyboardSend.KeyDown(Keys.LWin);
KeyboardSend.KeyDown(Keys.D4);
KeyboardSend.KeyUp(Keys.LWin);
KeyboardSend.KeyUp(Keys.D4);
Angelo Cresta
  • 104
  • 1
  • 7
-2

You need to use a global keyboard hook to hook into keyboards outside your application. There's an article on how to do it here.

Pete OHanlon
  • 9,086
  • 2
  • 29
  • 28