How to Know Which Modifier Key Was Pressed

How to Know Which Modifier Key Was Pressed

Added by Sixth Sense updated on Wednesday, March 28, 2018

How to Know Which Modifier Key Was Pressed?:

While handling the KeyPress event or a mouse event, the event handler does not receive which modifier keys are pressed. In this case, we must use the ModifierKeys property of the Control class.

To determine which modifier key was pressed:

We must use the bitwise AND operator with the ModifierKeys property and a value of the Keys enumeration to determine whether a particular modifier key is pressed.

Is SHIFT key is pressed:

public void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
	if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
	{
		MessageBox.Show("Pressed " + Keys.Shift);
	}
}				
				

Is CTRL key is pressed:

public void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
	if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
	{
		MessageBox.Show("Pressed " + Keys.Control);
	}
}				
				

Is ALT key is pressed:

public void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
	if ((Control.ModifierKeys & Keys.Alt) == Keys.Alt)
	{
		MessageBox.Show("Pressed " + Keys.Alt);
	}
}				
				

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected