Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - Global Windows Key Press

I have a simple WPF application and I need to capture F1 key pressed in Windows (Operation System), even if my WPF window is minimized, or it isn't activated.

I have problems with detecting this. I searched on Internet and I found many results, but they didn't helped me.

For detecting a key pressed inside of application I used this simple code:

AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)KeyPressed);
private void KeyPressed(object sender, KeyEventArgs e)
{
      if (e.Key == Key.F1)
      {
           //my code went here
      }
}

But this doesn't work when my window isn't activated.

So, my question is: how to detect global key press?

I repeat: It is a WPF application.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No need to Keyboard Hooking. Just use RegisterHotKey (Defines a system-wide hot key) and UnregisterHotKey from Windows API. Try using these in C# from pinvoke.net or these tutorials:

There is a sample in Microsoft Forums.

You can use these modifiers and Virtual-Key Codes:

MOD_ALT      (0x0001)
MOD_CONTROL  (0x0002)
MOD_NOREPEAT (0x4000)
MOD_SHIFT    (0x0004)
MOD_WIN      (0x0008)

for example F1 key is VK_F1 (0x70).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...