Application Starting - detecting Shift Key pressed

  • Thread starter Thread starter Michael Moreno
  • Start date Start date
M

Michael Moreno

Hello,

I would like to cancel an action if the user holds the shift key while
the application is starting-up.
Would you know what is the best way to do so please?


Thanks,
Michael
 
I'm assuming the main question is about the [Shift] key (not cancelling an
action):

Just test the Control modifiers:

if ((System.Windows.Forms.Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
System.Diagnostics.Debug.WriteLine("Shift down");
}

This appears to work even for console applications (if you adda a
reference), which is quite nice...

Marc
 
I would like to cancel an action if the user holds the shift key while
the application is starting-up.
Would you know what is the best way to do so please?

If you do it from within the Form class, you can use the 'ModifierKeys'.
If you want to do it from Main(...) or anywhere else outside of the Form,
then you can use PInvoke:

[DllImport("user32.dll")]
static extern short GetKeyState(VirtualKeyStates nVirtKey);

int ks = GetKeyState(VirtualKeyStates.VK_SHIFT);
if ((ks & 0x80) != 0)
{
// SHIFT KEY is pressed
}

BTW the VirtualKeyStates is an enum defined at pinvoke.net:

http://pinvoke.net/default.aspx/user32.GetKeyState

But if you wanted you could just set the PInvoke signature to use an int
and pass 0x10.

-mdb
 
See my previous post - you don't actually need the PInvoke step, regardless
of whether you are working with a Form subclass.

Marc
 
See my previous post - you don't actually need the PInvoke step,
regardless of whether you are working with a Form subclass.

Yeah I saw that... that's a good point - thanks for the tip.

-mdb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top