Home > Software design >  How to use WndProc in a WPF application
How to use WndProc in a WPF application

Time:03-07

I know there have been quite a lot of questions about this answered here, but I can't understand what to do, since I am still a beginner in programming. So I have code that works as a global keyhook that works in WinForms. It detects when F9 is pressed even when app is minimized. But when rewriting code to wpf, i have some troubles with protected override void WndProc(ref Message m). Every other piece of code that is required I solved the error. Below are snippets of my code.

using System.Windows.Interop;

// 2. Import the RegisterHotKey Method
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);

In the constructor:

// 3. Register HotKey
int UniqueHotkeyId = 1;
int HotKeyCode = (int)0x78;
IntPtr windowHandle = new WindowInteropHelper(this).Handle;
Boolean F9Registered = RegisterHotKey(windowHandle, UniqueHotkeyId, 0x0000, HotKeyCode);

And the part where the errors are:

protected override void WndProc(ref Message m)
{
    // 5. Catch when a HotKey is pressed!
    if (m.Msg == 0x0312)
    {
        int id = m.WParam.ToInt32();
        
        if (id == 1)
        {
            //Do something
        }
    }
    
    base.WndProc(ref m);
}

Errors are at: protected override void WndProc(ref Message m) and base.WndProc(ref m);

Thanks for any answers.

CodePudding user response:

I solved the issue with the help of Arkane's answer. But the example code that worked is located here: https://blog.magnusmontin.net/2015/03/31/implementing-global-hot-keys-in-wpf/

  • Related