我正在尝试在Visual c#2012中注册一个全局热键,构建目标框架.NET3,在使用http://www.dreamincode.net/forums/topic/180436-global-hotkeys/作为教程之后,我得到了以下(缩写)文件:
GlobalHotkey.cs
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace barcodelabel
{
public class GlobalHotkey
{
private int modifier;
private int key;
private IntPtr hWnd;
private int id;
public GlobalHotkey(int modifier, Keys key, Form form)
{
this.modifier = modifier;
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}
public bool Register()
{
return RegisterHotKey(hWnd, id, modifier, key);
}
public bool Unregister()
{
return UnregisterHotKey(hWnd, id);
}
public override int GetHashCode()
{
return modifier ^ key ^ hWnd.ToInt32();
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
}
}
GlobalHotkeyConstants.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace barcodelabel
{
class GlobalHotkeyConstants
{
public const int NOMOD = 0x0000;
public const int ALT = 0x0001;
public const int CTRL = 0x0002;
public const int SHIFT = 0x0004;
public const int WIN = 0x0008;
//windows message id for hotkey
public const int WM_HOTKEY_MSG_ID = 0x0312;
}
}
我的Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace barcodelabel
{
public partial class Form1 : Form
{
private GlobalHotkey ghk;
protected override void WndProc(ref Message m)
{
if (m.Msg == GlobalHotkeyConstants.WM_HOTKEY_MSG_ID) {
MessageBox.Show("HOTKEY PRESSED");
}
base.WndProc(ref m);
}
public Form1()
{
InitializeComponent();
this.ghk = new GlobalHotkey(GlobalHotkeyConstants.SHIFT, Keys.F10, this);
}
private void Form1_Load(object sender, EventArgs e)
{
if (!this.ghk.Register())
{
MessageBox.Show("Hotkey could not be registered");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.ghk.Unregister();
}
}
无论我想选择哪种热键,都无法注册。我尝试使用http://hkcmdr.anymania.com/中的Hotkey Explorer检查热键是否已经被取走,但它只告诉我它是免费的。
我该怎么做才能解决这个问题?
答案 0 :(得分:3)
我已经在我的VS中记下了你的代码并且它运行正常。如果要查找错误,请不要仅检查布尔返回的表单API。如果返回False,请尝试使用GetLastError API。然后你会有一个错误代码。请参阅MSDN并获取错误说明。