sigmaxf
sigmaxf

Reputation: 8482

WPF Global Hotkey using the mouse button

So, I'm using this example to create a global hotkey in a WPF application:

https://blog.magnusmontin.net/2015/03/31/implementing-global-hot-keys-in-wpf/

It's pretty straightforward and works fine... but whenever I try to change the key to the mouse button, the middle one for example, it just does not work... In the list of keys from msdn, there is:

https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

VK_MBUTTON 0x04 Middle mouse button (three-button mouse)

Whenever I try to change the hotkey to any listed key, it works fine, except for mouse buttons.. anyone know why this happens and how to fix it?

Upvotes: 0

Views: 1114

Answers (1)

Il Vic
Il Vic

Reputation: 5666

CapsLock is a key so can be registered as an HotKey. The mouse middle button is a button, not a key. You simply can't use the same native method/code.

I suggest you to adopt the globalmousekeyhook library for your application. In this case the sample that you find on Magnus Montin's blog will become:

public partial class MainWindow : Window
{
    private IKeyboardMouseEvents m_GlobalHook;

    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
        m_GlobalHook = Hook.GlobalEvents();
        m_GlobalHook.MouseClick += m_GlobalHook_MouseClick;

        base.OnSourceInitialized(e);
    }

    private void m_GlobalHook_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Middle)
        {
            tblock.Text += "Middle mouse button clicked" + Environment.NewLine;
        }
    }

    protected override void OnClosed(EventArgs e)
    {
        m_GlobalHook.MouseClick -= m_GlobalHook_MouseClick;
        m_GlobalHook.Dispose();

        base.OnClosed(e);
    }
}

The only problem is that globalmousekeyhook library refers to System.Windows.Forms assembly and I do not know if it can be acceptable for you.

Upvotes: 4

Related Questions