8
我想注册一个热键,我翻译this C++代码,我写它:如何在C#中使用RegisterHotKey()?
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll")]
public static extern
bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, int vk);
[DllImport("user32")]
public static extern
bool GetMessage(ref Message lpMsg, IntPtr handle, uint mMsgFilterInMain, uint mMsgFilterMax);
public const int MOD_ALT = 0x0001;
public const int MOD_CONTROL = 0x0002;
public const int MOD_SHIFT = 0x004;
public const int MOD_NOREPEAT = 0x400;
public const int WM_HOTKEY = 0x312;
public const int DSIX = 0x36;
static void Main(string[] args)
{
if (!RegisterHotKey(IntPtr.Zero, 1, MOD_ALT | MOD_NOREPEAT, DSIX))
{
Console.WriteLine("failed key register!");
}
Message msg = new Message();
while (!GetMessage(ref msg, IntPtr.Zero, 0, 0))
{
if (msg.message == WM_HOTKEY)
{
Console.WriteLine("do work..");
}
}
Console.ReadLine();
}
}
public class Message
{
public int message { get; set; }
}
}
但它永远RegisterHotKey()
返回false。 我不知道有关方法传递的参数,IntPtr.Zero是是相当于为null,消息类的第二个参数需要的对象。有人可以澄清吗?任何帮助非常感谢!
见[这里](http://bloggablea.wordpress.com/ 2007/05/01 /全局热键,用网/) – Shai 2012-01-18 14:46:33
注意:您的MOD_NOREPEAT值是错误的。 https://msdn.microsoft.com/en-us/library/windows/desktop/ms646309(v=vs.85).aspx – 2016-09-24 15:51:00
你的榜样工程完美,如果你使用MOD_NOREPEAT和正确的GetMessage适当的恒定值()定义(其返回int,并使用从System.Windows.Interop命名空间MSG结构) – tigrou 2018-02-11 19:19:19