How to implement Global Hotkeys in C#?

ぃ、小莉子 提交于 2020-01-05 11:49:03

问题


I need to write an application which globally intercepts Alt+Shift+S.

What I did is I created a DLL which sets global hooks:

namespace Hotkeydll
{
    public class MyHotKey
    {
        public static void setHooks()
        {
            KeyboardHookProcedure = new HookProc(KeyboardHookProc);
            hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
        }

        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            //write something into file
        }


   }
}

Then I created a program which loads this DLL and set the hook:

using Hotkeydll;
namespace IWFHotkeyStarter
{
    class Program
    {
        static void Main(string[] args)
        {
            MyHotKey.setHooks();
        }
    }
}

Now the problem is that the hotkey doesn't work.

It looks like the DLL is not loaded permanently into memory. I see that I can delete the dll file from file system.

So please advise what I am doing wrong?

Should I use a different approach?

Thank you.


回答1:


Your Main() method sets the hooks, then immediately exits and terminates the program. Furthermore, you need a message loop to make the hook callback work. That requires a Windows Forms or WPF app. Using a real hot key instead of a hook now also becomes an option. Check this thread for an example, C# is further down the page.




回答2:


Keyboard hooks are usually not the right way to get global hotkeys.

Use RegisterHotkey whenever possible.



来源:https://stackoverflow.com/questions/4410955/how-to-implement-global-hotkeys-in-c

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