C# Detect ESC press key anywhere

前端 未结 3 1817
执念已碎
执念已碎 2020-12-20 08:16

I have a C# windowed application running and I want to close it when I press ESC from anywhere, even when my application does not have focus. How can I implement this?

3条回答
  •  庸人自扰
    2020-12-20 08:29

    For those looking for a complete solution to detect global key presses and also make key presses, I've figured it all out and put the code in pastebin.com to "never" be deleted. Note especially InterceptKeys.cs here (do a Ctrl+F):

    http://pastebin.com/u7FUhgYr

    ^ This code is complete, but it's sub-optimal.


    Then I improved the code a bit (one change is the new SendKeys function I created which sends whatever key presses/releases you want - much easier to use!). This class here, MakroKeys:

    http://pastebin.com/Dedx6hRw

    has two static functions that can be used to convert from string to System.Windows.Forms.Keys and vice versa (which would be useful if you want the user to be able to input their own key via text and/or display the currently pressed key via text); and this has the improved MainForm.cs code to go with it (containing the SendKeys function):

    http://pastebin.com/BXzmWeMK

    (Note the MakroKeys.GetKey("lcontrolkey") call, which demonstrates the usage of that functionality.)


    With all of this combined you can do some pretty amazing things. Note also that because this is importing DLL's and calling Windows API functions, you can do this rather easily in e.g. c++ too. You're welcome, world. ;)

提交回复
热议问题