Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture Key press globally but suppress only for current app and child windows regardless of focus

I'm running into a weird problem. I have a WinForms application that opens another program (billing system emulator), sets it as a child window and then disables it. This works fine, the user cannot send any keys to the that child window, and the winforms application does its thing, sending commands to the child window.

However, it's been discovered that pushing the shift or control, even if the winforms application doesn't have focus, causes an error in the billing system emulator as they aren't valid keys. Users have taken to not using the shift or control keys while the winforms app runs but that's obviously not a practical solution.

My attempted solution was:

  1. Global keyboard hook to capture when those keys are pressed.
  2. Overriding OnKeyDown in the winforms application to stop those keys.

That however still doesn't solve the problem of the shift and alt keys being sent to the child window when the winforms app is not in focus. I can stop shift and alt globally while the winforms app is running but I don't think that is valid. So I need to somehow in the global hook stop the keypress for the winforms app and its children but allow globally. Any ideas/thoughts?

This is my code.

like image 355
CGross Avatar asked Dec 06 '25 03:12

CGross


1 Answers

I don't think there's a good answer for your scenario... =\

Here's a hack you can try. It will "release" Control/Shift if they are down, then you send your message afterwards:

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int extraInfo);

    [DllImport("user32.dll")]
    static extern short MapVirtualKey(int wCode, int wMapType);

    private void button1_Click(object sender, EventArgs e)
    {
        if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
        {
            keybd_event((int)Keys.ShiftKey, (byte)MapVirtualKey((int)Keys.ShiftKey, 0), 2, 0); // Shift Up
        }
        if ((Control.ModifierKeys & Keys.Control) == Keys.Control) 
        {
            keybd_event((int)Keys.ControlKey, (byte)MapVirtualKey((int)Keys.ControlKey, 0), 2, 0); // Control Up
        }

        // ... now try sending your message ...
    }

This obviously isn't foolproof.

like image 144
Idle_Mind Avatar answered Dec 07 '25 16:12

Idle_Mind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!