Search code examples
c#buttonwindows-messages

Find out if a button is being held using Windows Messages


I have a program that uses windows messages to know if a button is being clicked or not :

IntPtr GetMsg(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);

            if ((Keys)vkCode == Keys.SomeKey)
            {
                /*Functions*/
            }
         }
     }

The buttons can be pressed anywhere and the program will still handle them.

Problem is, whenever a user is holding down a certain button, the function that the button does is repeated a lot of times in a short period of time. And even though the function is not that heavy - its still causes the computer to freeze or work slow for a couple of seconds.

If I know that the button is being held, I would simply do the function once.

Is there a flag or something in a windows message that indicates that the button is being held?


Solution

  • You can listen to the WM_KEYUP event and only execute the function then or execute the function once and lock it until you get WM_KEYUP.