2017-06-12 69 views
0

我试过本教程:https://www.youtube.com/watch?v=FL_y8GT1L7E 但是,我注册热键后,它已注册,但回调不起作用。 当调用WndProc时,keyPressed.Msg不等于0x0312,这意味着按下按键。 任何建议为注册的热键创建回调?使用user32.dll库(c#)注册热键回调

这是哪些寄存器和注销热键类:

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); 
    } 
} 
} 

和当前回调是这样的:

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

     base.WndProc(ref keyPressed); 
    } 

0x0312是键按压的窗口中的值。 但我设置了一个断点Console.WriteLine()但它永远不会到达那里。

这是一个Windows窗体应用程序。

+0

首先,我建议重写后以下[StackOverflow的规则(https://开头计算器.com/help/how-to-ask):'只包含足够的代码以允许其他人重现该问题。' –

+0

@SimoneCifani编辑。 –

回答

1

当您调用本机函数RegisterHotKey(...)时,您会错过窗口句柄(hWnd)。

试试这个:

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); 
    } 
} 

为了得到一个窗口的形式使用的手柄:

this.Handle 
+0

谢谢你的工作! 问题是我使用了'FindWindow()'函数,它使用特定的字符串来识别我的窗体的窗口,并且可能我输入了错误。 'this.Handle'对于获得当前窗口要好得多。 –