我最近使用Visual Studio2010在Visual C# .NET 2010中编写了一个程序作为Windows Forms应用程序。这个程序通过user32.dll函数"RegisterHotkey“使用全局热键。一切都运行得很好。例如,当注册的热键被按下时,我可以显示一个MessageBox。然后,今天,在Visual Studio中出现了一些奇怪的错误(与热键无关)(实际上,它只是一个未加载的图像)之后,RegisterHotkey函数就不再起作用了。
我没有更改热键代码中的任何内容。
当我在Visual Studio中调试时,我没有得到异常。有了断点,我发现代码在RegisterHotkey函数处停止了。当我从项目的"debug“文件夹执行.exe文件时,程序显示一个错误,指出”入口点"RegisterHotkey“在"user32”DLL“中找不到。
这很奇怪,因为它一直都在工作。
为了检查我的项目或代码是否是原因,我创建了一个新的Windows窗体应用程序并输入代码:
using System.Runtime.InteropServices;
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int RegisterHotkey(IntPtr Hwnd, int ID, int Modifiers, int Key);
[DllImport("kernel32", EntryPoint = "GlobalAddAtomA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern short GlobalAddAtom(string IDString);
private void Form1_Load(object sender, EventArgs e)
{
int atomid = GlobalAddAtom("hallo");
RegisterHotkey(this.Handle, atomid, 0, (int)Keys.A);
}
}
}这也产生了同样的错误。尝试调用RegisterHotkey函数时出现错误。这一次,我试图输入尽可能少的代码。
窗体没有控件,它所要做的就是在其Load事件中注册一个热键。
我的问题是:谁能告诉我为什么突然找不到RegisterHotkey了?我哪里搞错了吗?我该怎么做才能让它再次工作呢?
我尝试导入"user32.dll“而不是"user32”,但除了错误消息中的文本外,它没有更改任何内容。在这里,"user32“被替换为"user32.dll”。
编辑:我不知道这是否相关,但我使用的是Windows7专业版64位版本和.NET Framework4.0(不是客户端配置文件)
发布于 2013-02-07 01:04:33
这可能是因为函数名是RegisterHotKey,大写是K,而不是RegisterHotkey。
尝试完全按照pinvoke.net上的描述来声明它
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);https://stackoverflow.com/questions/14734592
复制相似问题