简体   繁体   中英

How to implement Global Hotkeys in C#?

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.

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.

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

Use RegisterHotkey whenever possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM