Eldar Azulay Eldar Azulay -4 years ago 168
C# Question

Callback for registered hotkey using user32.dll library (c#)

I tried this tutorial: https://www.youtube.com/watch?v=FL_y8GT1L7E
But after I register the hotkey, it is registered, but the callback just doesn't work.
When calling WndProc, the keyPressed.Msg doesn't equal to 0x0312 which means key press.
Any suggestions for creating a callback for a registered hotkey?

this is the class which registers and unregisters the hotkeys:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
class Hotkey
{
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

private IntPtr _hWnd;

public Hotkey(IntPtr hWnd)
{
this._hWnd = hWnd;
}

public enum fsmodifiers
{
Alt = 0x0001,
Control = 0x0002,
Shift = 0x0004,
Window = 0x0008
}

public void RegisterHotkeys()
{
RegisterHotKey(IntPtr.Zero, 1, (uint)fsmodifiers.Control, (uint)Keys.B);
}

public void UnregisterHotkeys()
{
UnregisterHotKey(IntPtr.Zero, 1);
}
}
}


and the current callback is this:

protected override void WndProc(ref Message keyPressed)
{
if(keyPressed.Msg == 0x0312)
Console.WriteLine();

base.WndProc(ref keyPressed);
}


0x0312 is the value of key press in windows.
but I set a breakpoint where
Console.WriteLine()
but it never gets there.

This is a windows forms application.

Answer Source

When you call the native function RegisterHotKey(...) you miss the window handle (hWnd).

Try this:

class Hotkey
{
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    private IntPtr _hWnd;

    public Hotkey(IntPtr hWnd)
    {
        this._hWnd = hWnd;
    }

    public enum fsmodifiers
    {
        Alt = 0x0001,
        Control = 0x0002,
        Shift = 0x0004,
        Window = 0x0008
    }

    public void RegisterHotkeys()
    {
        RegisterHotKey(this._hWnd, 1, (uint)fsmodifiers.Control, (uint)Keys.B);
    }

    public void UnregisterHotkeys()
    {
        UnregisterHotKey(this._hWnd, 1);
    }
}

To get the handle of a windows form use:

this.Handle
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download