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.
精彩评论