Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Ctrl key being held down on application startup?

Tags:

c#

.net

wpf

When our WPF application starts, it uses Single Sign On to log in. To allow testers to simulate other users, we'd like to detect the Control button being held down on startup, and pop up a login dialog.

like image 977
James L Avatar asked Jun 13 '11 16:06

James L


People also ask

Why does my computer think I am holding down the Ctrl key?

This could be caused by the 'Sticky Keys' function (an accessibility option). If you are on Windows 7, click on the start button go to Control Panel, ease of access, change how your keyboard works. Under the option 'Make it easier to type', uncheck 'Turn on Sticky keys' and see if this solves your problem.

How do I turn off Ctrl key?

Select the key that you want to disable. Under the Keyboard Controls section, select Disable Key. Click on Apply.

How do you check Ctrl key is working?

To check the physical state of your keyboard, you can try to connect an external keyboard on your system or try an on-screen keyboard and check if the Ctrl key is working on it or not. You can also try to connect your keyboard to another system to check if Ctrl key is working or not.


2 Answers

This is what I use in a WPF app to check if the control key is being held down in the constructor of the main Window. It uses System.Windows.Input.Keyboard

if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)
    PromptForMarketSelection();

EDIT - corrected bug pointed out by Coincoin

like image 175
BrandonAGr Avatar answered Sep 30 '22 15:09

BrandonAGr


A universal solution would be to p/invoke GetAsyncKeyState(VK_CONTROL), in case you can't find anything built into .NET.

like image 40
Ben Voigt Avatar answered Sep 30 '22 15:09

Ben Voigt