Trying to detect keypress - c#

I made a method that detects when a key is pressed, but its not working! Heres my code
void KeyDetect(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W && firstload == true)
{
MessageBox.Show("Good, now move to that box over to your left");
firstload = false;
}
}
I also tried to make a keyeventhandler but, it sais "cannot assign to key detect because it is a method group"
public Gwindow()
{
this.KeyDetect += new KeyEventHandler(KeyDetect);
InitializeComponent();
}

Use keypress event like this:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyCode == Keys.F1 && e.Alt)
{
//do something
}
}

1) Go to your form's Properties
2) Look for the "Misc" section and make sure "KeyPreview" is set to "True"
3) Go to your form's Events
4) Look for the "Key" section and double click "KeyDown" to generate a function to handle key down events
Here is some example code:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("You pressed " + e.KeyCode);
if (e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0)
{
//Do Something if the 0 key is pressed (includes Num Pad 0)
}
}

You are looking for this.KeyPress. See How to Handle Keypress Events on MSDN.

Try to use the KeyDown event.
Just see KeyDown in MSDN

Just do
if (Input.GetKeyDown("/* KEYCODE HERE */"))
{
/* CODE HERE */
}

Related

Keydown event how to listen with hotkey

I have registed ctrl+` as a hotkey,and I want to display a window when I press the hotkey and not release the leftctrl key and toggle ` key to do something else just like alt+tab switch the application.Here is the code.
private void ListOnKeyDown(object sender, KeyEventArgs e)
{
if (e.SystemKey==Key.LeftCtrl && e.Key == Key.Oem3)
{
m_host.SelectNext();
}
}
But I found this way only fired one key.So what's the right way to fire the key event?
And here is the debug information.
debug information
Just change your keydown event to detect the modifier this way
private void ListOnKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Oem3)
{
m_host.SelectNext();
e.Handled = true;
}
}
Because onKeyDown event works for ONE key only, in order to use two keys at same time you need little improvise:
bool firstkeyisOn = false;
private void ListOnKeyDown(object sender, KeyEventArgs e)
{
if (e.SystemKey==Key.LeftCtrl/*Or other key by choice*/)
{
firstkeyisOn = true;
e.Handled = true;
return;
}
if(firstkeyisOn && (e.Key == Key.Oem3/*Or other key by choice*/))
{
m_host.SelectNext();
}
}
private void ListOnKeyUp(object sender, KeyEventArgs e)
{
if (e.SystemKey==Key.LeftCtrl/*Key must be same as holding one*/)
{
firstkeyisOn = false;
}
//or
//firstkeyisOn = false;
}
To cancel hotkey mode you just add firstkeyisOn = false under OnKeyUp event and you good to go.

Save a text string to textbox with keyboard shortcut

Im a beginner in C# and im trying to create a windows form application that save a copied text to a textbox when you execute a command with the keyboard. I know there is mouch more to do but where do i start? I suceed to make someting happening with the code below a start at least..
And another question.. is it possible to create more than 2 commands. It doesn't work if i add for example : " && KeyCode.ToString() == "B") "
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode.ToString() == "C")
{
MessageBox.Show("CTRL+C");
}
}
Cheers
You would manage this by calling keyDown/Up events. Keep track of each event and which key went down. Then using the Clipboard.GetText() function to copy/paste the text from clipboard into your textbox once both keys are down.
Example,
bool keyup = false;
bool keyleft = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
keyup = true;
}
else if (e.KeyCode == Keys.Left)
{
keyleft = true;
}
if (keyleft && keyup)
{
textboxOne.Text = Clipboard.GetText(TextDataFormat.Html);
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
keyup = false;
}
else if (e.KeyCode == Keys.Left)
{
keyleft = false;
}
}
Used both these as my resources.
Resource One: Detect when two keys are pressed at the same time
Resource Two: http://msdn.microsoft.com/en-us/library/c2thcsx4%28v=vs.110%29.aspx

How can I determine in KeyDown that Shift + Tab was pressed

How can I determine in KeyDown that ⇧ + Tab was pressed.
private void DateTimePicker_BirthDate_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Modifiers == Keys.Shift)
{
//do stuff
}
}
can't work, because never both keys are pressed exactly in the same second. You always to at first the Shift and then the other one..
It can't work, because never both keys are pressed exactly in the same second.
You're right that your code doesn't work, but your reason is wrong. The problem is that the Tab key has a special meaning - it causes the focus to change. Your event handler is not called.
If you use a different key instead of Tab, then your code will work fine.
If you really want to change the behaviour of Shift + Tab for one specific control, it can be done by overriding ProcessCmdKey but remember that many users use the Tab key to navigate around the form and changing the behaviour of this key may annoy those users.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (DateTimePicker_BirthDate.Focused && keyData == (Keys.Tab | Keys.Shift))
{
MessageBox.Show("shift + tab pressed");
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}
If you are looking for a key press combination (Tab, then Shift) like Ctrl K + D you will have to use this modified example which was taken from MSDN social.
private StringBuilder _pressedKeys = new StringBuilder();
private void DateTimePicker_BirthDate_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
_pressedKeys.Append("Tab");
return;
}
if (e.Modifiers == Keys.Shift)
{
_pressedKeys.Append("Shift");
return;
}
if (_pressedKeys.ToString()."TabShift")
{
MessageBox.Show("It works!");
_pressedKeys.Clear();
}
else
{
_pressedKeys.Clear();
}
base.OnKeyDown(e);
}
First hook the Tab keypress event, then during the event, check the state of the Shift key. Keep in mind that there are two shift keys; make sure you check both of them.
This very related post shows how to check the state of modifier keys:
How to detect the currently pressed key?
Edit: an insight provided by another answerer who justly deserves an upvote is that the default behavior of the tab key (to change control focus) must be suppressed.
You can find your answer in
this post
It's Simple.
You can do that using KeyUp Event in the TextBox
private void txtBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Shift == false) // TAB Key Pressed
{
}
if (e.KeyCode == Keys.Tab && e.Shift == true) // TAB + SHIFT Key Pressed
{
}
}
Or
Using this you can identify Any Key is press inside the form
//Add This code inside the Form_Load Event
private void Form1_Load(object sender, EventArgs e)
{
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyPressEvent);
this.KeyPreview = true;
}
//Create this Custom Event
private void KeyPressEvent(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Shift == false) // TAB Key Pressed
{
}
if (e.KeyCode == Keys.Tab && e.Shift == true) // TAB + SHIFT Key Pressed
{
}
}
It's Simple.
Using this you can identify Any Key is press inside the form
//Add This code inside the Form_Load Event
private void Form1_Load(object sender, EventArgs e)
{
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyPressEvent);
this.KeyPreview = true;
}
//Create this Custom Event
private void KeyPressEvent(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Shift == false) // TAB Key Pressed
{
}
if (e.KeyCode == Keys.Tab && e.Shift == true) // TAB + SHIFT Key Pressed
{
}
}

Handle the KeyDown Event when ALT+KEY is Pressed

How do you handle a KeyDown event when the ALT key is pressed simultaneously with another key in .NET?
The KeyEventArgs class defines several properties for key modifiers - Alt is one of them and will evaluate to true if the alt key is pressed.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyData != (Keys.RButton | Keys.ShiftKey | Keys.Alt))
{
// ...
}
}
Something like:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt)
{
e.Handled = true;
// ,,,
}
}
This is the code that finally Works
if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z && e.Alt){
//Do SomeThing
}
I capture the alt and down or up arrow key to increment the value of a numericUpDown control. (I use the alt key + down/up key because this form also has a datagridview and I want down/up keys to act normally on that control.)
private void frmAlzCalEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.Down)
{
if (nudAlz.Value > nudAlz.Minimum) nudAlz.Value--;
}
if (e.Alt && e.KeyCode == Keys.Up)
{
if (nudAlz.Value < nudAlz.Maximum) nudAlz.Value++;
}
}
Create a KeyUp event for your Form or use a library like I did to get a GlobalHook so you can press these keys outside the form.
Example:
private void m_KeyboardHooks_KeyUp(object sender, KeyEventArgs e)
{
if ( e.KeyCode == Keys.Alt || e.KeyCode == Keys.X)
{
}
}

Problems Detecting Alt Key on the Control.KeyUp event

I have a control with KeyDown and KeyUp events as shown below. The problem I am having is that 'x' is TRUE in KeyDown but always FALSE in KeyUp. I am trying to detect the Alt key (as you may have guessed).
Is there a gottcha that I don't know. I mean, when I press Alt it detects it ok but on keyup it's false.
Any suggestions/ideas
Thanks
private void MyControl_KeyDown(object sender, KeyEventArgs e)
{
bool x;
x = ((int) (e.KeyData & Keys.Alt) != 0);
x = (e.KeyData & Keys.Alt) == Keys.Alt;
x = e.Alt;
}
private void MyControl_KeyUp(object sender, KeyEventArgs e)
{
bool x;
x = ((int) (e.KeyData & Keys.Alt) != 0);
x = (e.KeyData & Keys.Alt) == Keys.Alt;
x = e.Alt;
}
Are you trying to detect an Alt+[letter] event? Is so, try this:
private void YourControl_KeyDown(object sender, KeyEventArgs e)
{
if((e.Alt) & (e.KeyCode == Keys.X))
{
MessageBox.Show("Alt-X pressed");
}
}
For just Alt, try this:
private void YourControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Menu)
{
//YourCode
e.Handled = true;
}
}
private void YourControl_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Menu)
{
//YourCode
e.Handled = true;
}
}
I hope you're not just setting a bool member variable in your class in response to the Alt key being pressed.
If you want to know if the Alt key is down while executing code in response to other events (eg mouse events) use the Control.ModifierKeys property as it is far more reliable. It also means you don't have a redundant member variable.
If you are actually trying to detect if the user has pressed just a Modifier key by itself then #bluecoder's solution is probably what you want.
If you want detect real key pressing (Alt or any other key), you can use this code. This code works in the KeyUp, KeyDown and other key events
private void YourControl_KeyDown(object sender, KeyEventArgs e)
{
Key _key = e.Key != Key.System ? e.Key : e.SystemKey;
// _key is your real pressed key
}

Categories