Click here to Skip to main content
12,814,411 members (40,555 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# keypress
Hey guy, what is the best way to detect if Control key, or Shift key is pressed, without my form is on focus
Posted 10-Apr-13 13:35pm
Sergey Alexandrovich Kryukov 10-Apr-13 18:43pm
System.Windows.Forms? Tag: "WinForms". Something else? Tag it properly.
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...
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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:[^].

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.

Rate this: bad
Please Sign up or sign in to vote.

Solution 2

if ((Control.ModifierKeys & Keys.Shift) != 0)

This will be true if shift key is down..

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

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170308.1 | Last Updated 11 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100