2
votes

I recently made a program in Visual C# .NET 2010 as Windows Forms Application using Visual Studio 2010. This program uses global Hotkeys through the user32.dll-function "RegisterHotkey". Everything worked just fine. I was able to show a MessageBox when a registered Hotkey was pressed (for example). Then, today, after some strange Errors in Visual Studio (which had nothing to do with Hotkey) (in fact it was just an image that wasn't loaded) the RegisterHotkey function doesn't work anymore.

I didn't change anything in the hotkey code.

When I debug in Visual Studio, I get no exception. With a breakpoint I found out that the code stopped at the RegisterHotkey function. When I execute the .exe file from the "debug" folder of the project the program shows an error that states that the "entry point "RegisterHotkey" wasn't found in the "user32" DLL".

Which is strange, cause it worked the whole time.

To check if my project or code was the reason, I created a new Windows Forms Application and entered the code:

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

Which produced the same error. The error occurs when trying to call the RegisterHotkey function. I tried to enter the least amount of code possible this time.

The form has no controls and all it is supposed to do it registering a hotkey in its Load event.

My question is: Can anybody tell me why RegisterHotkey isn't found anymore all of sudden? Did I make a mistake anywhere? And what can I do to make it work again?

I tried to import "user32.dll" instead of "user32" but it didn't change anything except for the text in the error message. There, "user32" was replaced by "user32.dll".

EDIT: I don't know if it's relevant or not but I use Windows 7 Professional 64 bit version and .NET framework 4.0 (not the client profile)

1

1 Answers

2
votes

It probably happens because the function name is RegisterHotKey, with capital K, not RegisterHotkey.

Try to declare it exactly as described on pinvoke.net:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);