Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guy, what is the best way to detect if Control key, or Shift key is pressed, without my form is on focus
Posted
Comments
Sergey Alexandrovich Kryukov 10-Apr-13 18:43pm    
System.Windows.Forms? Tag: "WinForms". Something else? Tag it properly.
—SA
Sergey Alexandrovich Kryukov 10-Apr-13 19:07pm    
Why doing so? You should better explain your ultimate goals, that way you could get an advice even if the technical approach you might be preoccupied with is wrong...
—SA

This is impossible if you use .NET FCL, because this is not really needed. For your information, "focus" means "keyboard focus" and nothing else. The difference you see on screen is no more than a visual clue to show the focus. As a form has no keyboard focus, it does not accept keyboard events at all, by definition.

You still can capture the keyboard and many other events dispatched to the processes other then your application, but it is impossible to do with pure C#. It looks like the only way to capture such event it the Windows Hook: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632589%28v=vs.85%29.aspx[^].

So, why cannot you simply install such hook with C# and P/Invoke? Well, because, it has to be the Global Hook, as you need to capture keyboard events system-wide. And, according to Microsoft Hook documentation, the hook function should reside in a separate native (unmanaged) DLL. You can create such DLL, but not using C#. Then you can develop some mechanism to load DLL and communicate between this DLL and your .NET application. I've done this with unmanaged application, but it's not a problem to do it with .NET.

—SA
 
Share this answer
 
C#
if ((Control.ModifierKeys & Keys.Shift) != 0)


This will be true if shift key is down..
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900