How to set HotKey system-wide in C#

穿精又带淫゛_ 提交于 2019-12-08 02:36:06

问题


In AutoIt v3 there's a function called HotKeySet. It sets a hotkey that calls a user function when pressed. It's a system wide hotkey, meaning that the key can't be used for anything else when the hotkey is set.

Basically, I would like to catch Esc or any other key like $, `, etc. and when the user presses it anywhere, even outside of the application, it should let me know.

For example, I would do like HotKeySet({ESC}) inside a loop and when it's done, the program would wait for that key to be pressed before.

public static void work() {
    while (true) {
        string task = null;
        lock (locker)
            if (tasks.Count > 0) {
                task = tasks.Dequeue();
                if (task == null) {
                    return;
                }
            }
        if (task != null) {
            //MessageBox.Show("Performing task: " + task);
            Program.mainAnnounceWindow.setLogTextBox(task);
            Program.mainAnnounceWindow.setLogTrayTip(task);
            Program.windowStateChange("Show");

            // Set the hotkey here
            SetHotkey(`);

            //Wait for hotkey to press when it's pressed... Execute some stuff
            Thread.Sleep(5000); // Simulate work...
            Program.windowStateChange("Hide");
        }
        else {
            wh.WaitOne(); // No more tasks - wait for a signal
        }
    }
}

回答1:


You need to take a look at RegisterHotKey in user32.dll. There a good example at pinvoke.net, RegisterHotKey (user32).




回答2:


I think you need to setup a system hook...

Here is an example: http://www.axino.net/tutorial/2009/02/keylogger-in-c-introduction



来源:https://stackoverflow.com/questions/2194752/how-to-set-hotkey-system-wide-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!