I got a question about KeyCode and disabling special keys. I know this question was asked a few times, but I didn't find an answer I can use and which works so I came here to ask :)
I'm writing a program which blocks every key or key combinations (like Alt+F4 etc.). The application is not for me, it's for customers which only be able to navigate in this program. This all works fine, but I can't disable Left CTRL, Right CTRL or Alt key. I got this code for try blocking these keys:
private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.LControlKey)
{
MessageBox.Show("LCtrl", "Warnung", MessageBoxButtons.OK);
}
else if (e.KeyCode == Keys.RControlKey)
{
MessageBox.Show("RCtrl", "Warnung", MessageBoxButtons.OK);
}
else if (e.KeyCode == Keys.Alt)
{
MessageBox.Show("Alt", "Warnung", MessageBoxButtons.OK);
}
else if (e.KeyCode == Keys.Delete)
{
MessageBox.Show("Delete", "Warnung", MessageBoxButtons.OK);
}
}
I only use MessageBox.Show(); that I can see if it works. Delete key works fine, but the other one not. Is it possible to do this without editing the registry and for Win7? Does anyone know why or can give me a hint?
Cheers
EDIT: I block all other keys in this way:
Blocking shortcut keys using c#
Disclaimer: I'm not highly experienced in user input classes, but here's my input.
CTRL and ALT are examples of modifier keys. That is to say, they modify other (non-modifier) keys to create a key combination. Your UI is likely only able to pick up a complete key combination. For example:
private void keyPressed(object sender, PreviewKeyDownEventArgs e)
{
e.KeyCode == Key.A; // True (pressed A)
e.KeyCode == Key.Control; // False (no key pressed)
e.Modifiers == Keys.Control; // True (user is pressing the modifier CTRL)
e.KeyCode == Key.A && e.Modifiers == Keys.Control; (pressed key A with modifier CTRL)
}
As for disabling the key, you could just catch e.Modifiers:
private void ignoreCtrl(object sender, PreviewKeyDownArgs e)
{
if (e.Modifiers != Keys.Control) { /* Pass to handler */ }
else { /* Discard */ }
}
Again, I'm not experienced in your particular framework but this would be my guess. I used the following SO sources:
How to use multiple modifier keys in C#
Determine whether modifier key was pressed
This should be a comment because I have not tested it, but I need some code as example so I write here. You tell me if it works or not.
The PreviewKeyDownEventArgs contains other properties that you can use to check if one or more modifier keys are pressed.
You can then try to set the IsInputKey property to false to prevent further processing for whatever regular key has been pressed together the modifier key.
private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
if (e.Control)
{
MessageBox.Show("Ctrl", "Warnung", MessageBoxButtons.OK);
e.IsInputKey = false;
}
else if (e.Alt)
{
MessageBox.Show("Alt", "Warnung", MessageBoxButtons.OK);
e.IsInputKey = false;
}
Have you tried checking the modifier keys? Such as below.
Note this is for WPF as you didnt state win forms or wpf.
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
MessageBox.Show("Control Button Down");
}
else if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt)
{
MessageBox.Show("Alt Down");
}
Cheers.
Related
I know that I can have a key press event like this-
private void FormMain_KeyDown(object sender, KeyEventArgs e){
//Pressing Control + N
if(e.KeyData == (Keys.Control | Keys.N)) MessageBox.Show("e");
}
But is there any way I can check to see whether the space key is pressed in a different function? I know that I can check to see if the CTRL key is being pressed, like this
if (Control.ModifierKeys == Keys.Shift)
I tried the following code, but it doesn't work. Is there a way to do it like this?
if (Control.ModifierKeys == Keys.Space)
I have to catch user's input to send a shortcut to my WPF application.I found on internet that I have to do something like this: Catch when a key is pressed:
void keyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers.HasFlag(Modifiers.Shift))
KeyPressed.SetShift(true);
if (Key.Shift != e.Key && Key.LeftAlt != e.Key && ....)
KeyPressed.SetKey(e.Key);
}
where KeyPressed is a class with static boolean variables to catch if ⇧Shift, Alt or Ctrl and another key are pressed (with Alt and Ctrl instead of ⇧Shift in the if clause). The second if is to catch a key different from Alt, ⇧Shift, Control for the shortcut. For example, for the shortcut Alt+C we have:
KeyPressed.Shift = false;
KeyPressed.Alt = true;
KeyPressed.Ctrl = false;
KeyPressed.key = Key;
Where the last element is of type System.Window.Input.Key.Catch when a key is released:
void keyUp(object sender, KeyEventArgs e)
{
if (KeyPressed.getShift())
this.textField.Text += "+Shift";
if (KeyPressed.getKeyCode())
this.textField.Text += "+" + KeyPressed.k.toString();
KeyPressed.SetShift(false);
}
and here simply I append to a textField the input received, after that I set all keys to false to catch the next shortcut correctly. This code works fine for all shortcuts like Ctrl+A, Ctrl+Alt+C, ⇧Shift+L, Alt, but when I press the shortcut like Alt+V, it catchs only Alt, not the other key.
How can I manage this? Is there a way to handle shortcuts in a better manner?
You need to get the actual key when in case of a SystemKey (Alt etc), you can use this helper function to get the real key behind the system key.
public static Key RealKey(this KeyEventArgs e)
{
switch (e.Key)
{
case Key.System:
return e.SystemKey;
case Key.ImeProcessed:
return e.ImeProcessedKey;
case Key.DeadCharProcessed:
return e.DeadCharProcessedKey;
default:
return e.Key;
}
}
You could check my answer here for more info.
Store the Alt-modifier state in a local variable. I'm unsure of the reasons why but this made it work for me.
private bool _altModifierPressed = false;
private void Window_KeyDown(object sender, KeyEventArgs e)
{
_altModifierPressed = (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt));
if (_altModifierPressed && Keyboard.IsKeyDown(Key.V))
{
// code to handle Alt + V
}
}
UPDATE:
Alternatively, you could do something like this (no need for local variable)
if (((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) && Keyboard.IsKeyDown(Key.V))
{
// code to handle Alt + V
}
But I noticed that with either approach (since the enum has the Flag attribute) any combination of keys including Alt & V will work. So both execute if I for example press Alt+G+V. Good luck.
If you want to use [Alt + A] in KeyboardHook in Office VSTO, this is how it's used.
if (IsKeyDown(Keys.Menu) &&
keyData == Keys.A &&
KeyWasAlreadyPressed == false &&
!IsKeyDown(Keys.Controlkey) &&
!IsKeyDown(Keys.ShiftKey))
{
//Enter your code here
}
Note:
Key.Menu denotes Alt Keys
Also condition says, Alt+A (and do not invoke when control or shift key is pressed in addition to Alt + A)
switch (e.Key)
{
case Key.System:
if (((KeyboardEventArgs)e).KeyboardDevice.Modifiers == ModifierKeys.Alt)
{
if (e.SystemKey == Key.Left)
moiveVideoPsition(-30);
else if (e.SystemKey == Key.Right)
moiveVideoPsition(30);
}
break;
This work well for me
I use a MaskedTextBox control to facilitate the entry of dates in my project. I have mtb.BeepOnError set to false. However, it makes a generic beep whenever the 'Enter' key or 'Esc' key is pressed, and this is undesirable for my application.
This seems to be the default behaviour for the MTB, so is there any way to change that?
You can try something like this:
void mtb_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter | e.KeyCode == Keys.Escape) {
e.SuppressKeyPress = true;
}
}
I'm trying to detect when the user presses the Return key while in a Winforms textbox, but neither control statement below works when I use Keys.Enter and/or Keys.Return. It does work when I detect other keys such as Alt and Shift. What am I missing? They only vague lead that I have is that I'm testing this on a MacBook keyboard (running Windows), but surely those keys are mapped 100% correctly?
private void txtInput_KeyUp(object sender, KeyEventArgs e)
{
if ((Control.ModifierKeys == Keys.Enter))
{
btnOK_Click(null, null);
}
if ((Control.ModifierKeys & Keys.Return) != 0)
{
btnOK_Click(null, null);
}
}
Try using:
e.KeyCode == Keys.Enter
Control.ModifierKeys catch only if ctrl,alt,shift are pressed!
if you need catch only 'enter' pressed w/o any key pressed use:
e.KeyData == Keys.Enter
I have a textbox on a form where I'm trying to detect the keys the user types in. The TextBox is multilined with wordwrap on. I don't want the user the press the enter key (as I want all text entered on ONE line, wrapped) so I used the following code:
private void txtPlain_KeyPress(object sender, KeyPressEventArgs e) {
if (e.KeyChar == (char)13) {
MessageBox.Show("Enter keys are not allowed");
e.KeyChar = (char)0;
}
}
This worked fine in my tests, but when I tested for CTRL+ENTER it didn't work as I'm not sure how to detect for the control key. From my googling I found that I need to use the KeyUp/Down events so I now have the following Code:
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
}
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
The problem with the KeyUp/Down event is that I don't know how to REMOVE the enter key from the text - unlike the KeyPress event when I can set the KeyChar to zero. The event captures both the Enter and Ctrl+Enter keys, but the cursor still goes to the next line in the TextBox.
Thanks for any help on this.
Hmm, there's no reason to disallow the Enter key by handling the KeyDown or KeyUp events. You can simply set the AcceptsReturn property of the textbox control to False. This will prevent a multiline textbox from responding to a press of the Enter key.
Of course, this doesn't solve the problem of Ctrl+Enter. In fact, that's the expected way to create a new line when the AcceptsReturn property is set to False. To solve that, you will need to handle one of the keyboard events and prevent the control from receiving this input.
KeyDown is a good place to start. What you want to do is filter out any keyboard events that include the Keys.Enter flag. That will catch them no matter which other modifier key they might be combined with. Then, once you've found an Enter keypress, you want to set the e.Handled property to True in order to prevent it from being passed on to the control.
But unfortunately, we're not quite done yet. The textbox control tries to handle certain keys internally, and you're not going to be able to override that in a key event handler method. You also need to tell the control not to interpret that particular key as an input key. There are two primary ways of doing this. The first (and recommended way) is to inherit from the base TextBox class to create your own custom control, and then override the protected IsInputKey method. The second (somewhat simpler) way is just to handle the PreviewKeyDown event, and set the IsInputKey property to False.
Sample code:
private void txtPlain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Set the IsInputKey property to False
e.IsInputKey = false;
}
}
private void txtPlain_KeyDown(object sender, KeyEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Show the user a message
MessageBox.Show("Enter keys are not allowed in this textbox.");
// Prevent the key event from being passed on to the control
e.Handled = true;
}
}
And, though I assume this is for testing purposes only, you definitely want to take that MessageBox call out of there for production code. Find another way to alert the user that their input was not allowed, such as a short beep sound and an ErrorProvider component placed next to the textbox. Showing a message box is very jarring, and not very user-friendly. See my answer here for other hints and tips.
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
// mark event as handled
e.Handled = true;
}
}
from msdnlink
edit:
I think that you need the key down event not the key up
EDIT2
here is some tested code and it works as you wanted:
bool invalid=false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
invalid = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (invalid)
{
e.Handled = true;
}
invalid = false;
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
You wanted to detect Ctrl + Enter.
if (e.KeyData == (Keys.Control | Keys.Enter)) {..
Keys.Control and Key.Enter are nothing but are some values please refer . Now doing logical or will not necessarily result to key which has been pressed. Totally illogical clause.
Ok now come to your actual problem you want to detect Enter stroke and Ctrl + Enter stroke to be treated as same.
Besides you want to undo the newline character thats been introduced. Try
PreviewKeyDown or Preview key up eventhandler with the following condition
if(e.KeyCode==Keys.Enter)
Let me know if this works