I'm adding hotkey support to an app, and throughout, I use CTRL+ENTER as the hotkey for confirming dialogs.
I'm having a unique issue in the dialog below, which contains a ListBox. If the ListBox has the focus (it usually does) when the CTRL+ENTER hotkey is pressed, it intermittently shifts the ListBox selection down one position.
This creates a problem, since changing the selected item in the ListBox updates the New Customer Name field. What's happening is users choose the settings they want, hit CTRL+ENTER to execute the merge, and the settings suddenly change just before the merge occurs.
I'm not handling any key events on the ListBox, and the selection change is weirdly intermittent (perhaps 1 in 8 times). I also can't seem to get ENTER or CTRL+ENTER to cause selection changes intentionally.
What causes this behavior, and how do I suppress it?
Hotkey Handling
The approach I'm using to Form-level hotkey handling is to set Form.KeyPreview = true and to handle the KeyUp event. Based on this SO post, this is the cleanest way to support the handling of modifier keys, and it seems to work like a charm.
private void frmMerge_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Escape:
Close(); // Close Form
return;
case Keys.Enter:
if (e.Control) // CTRL+ENTER
ActionMerge(); // Merge Customer
return;
}
}
ListBox Use
The ListBox is setup very simply. It is populated once on Form Load;
private void frmMerge_Load(object sender, EventArgs e)
{
// Add all Customers to the list
foreach(Customer customer in Customers)
{
lbxNames.Items.Add(customer.Name);
}
// If there are items, select the first one
if (lbxNames.Items.Count > 0)
lbxNames.SelectedIndex = 0;
}
And it handles one event, SelectedIndexChanged, to update the New Customer Name TextBox
private void lbxNames_SelectedIndexChanged(object sender, EventArgs e)
{
txtName.Text = lbxNames.SelectedItem as string;
}
These are the only two places that the ListBox is touched in code.
I've found a workaround to the problem, but not determined the cause. My best guess is that I'm dealing with a keyboard hardware or driver issue, rather than a ListBox issue.
The intermittent nature of the problem was caused by the CTRL+M hotkey combination, which is used to open my Merge dialog. That M appears to stick in a key queue somewhere, perhaps in the hardware keyboard buffer or driver. On executing the CTRL+ENTER hotkey, that M fires a second time. In the ListBox, pressing M only shifts the selected record if there is a record beginning with M.
Workaround
I made two changes. First I suppress the M key in the ListBox. This works fine for me, since I only need arrow key and home/end navigation in the ListBox, and not alphabetic selection.
private void lbxNames_KeyDown(object sender, KeyEventArgs e)
{
// Suppress listbox hotkeys to prevent dialog hotkey conflicts
switch (e.KeyCode)
{
case Keys.M:
e.Handled = true;
e.SuppressKeyPress = true; // required
break;
}
}
Second, I changed my dialog-level hotkeys handler to use the ProcessCmdKey approach in place of KeyUp. The reason for this is that using KeyUp event handlers conflicted strangely between the Form level and the ListBox level. Many keys would get captured by the ListBox first, even with KeyPreview enabled.
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.Escape:
// Close the dialog
Close();
return true;
case Keys.Control | Keys.Enter:
// Perform the primary action
ActionMerge();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Related
Users will usually expand the ComboBox, pick the desired option and the ComboBox will hide other options. Now user can delete the chosen option by pressing backspace button. May I know how to prevent it?
This could be avoided by handling the PreviewKeyDown event and marking any use of the backspace key as handled
void OnComboPreviewKeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Back) {
e.Handled = true;
}
}
You could set its DropDownStyle to DropDownList if you don't want it to be editable at all.
Steps to reproduce in VS Express 12:
Create a new Windows Forms Application project
Add a button
Set the Form KeyPreview to true
Add a keyDown event to the form
The event will not trigger as long as the button is present on the form
I have a project where I want to catch both keydown and keyup events, however, I can only seem to get the keyup event to work.
I have a form with a single panel, button and label on it. In the form the keyPreview property is set to true, and is linked to both the KeyDown and KeyUp events.
However, when I run the program, only the KeyUp event triggers.
I tried adding the event handlers manually by adding
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
But it still does not work.
Any suggestions?
KeyUp event:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
TriggerKey(e.KeyCode, false);
}
private void TriggerKey(Keys e, Boolean pKeyDown)
{
switch (e)
{
case Keys.Left:
mLeft = pKeyDown;
break;
case Keys.Right:
mRight = pKeyDown;
break;
case Keys.Down:
mDown = pKeyDown;
break;
case Keys.Up:
mUp = pKeyDown;
break;
}
}
My Form1_KeyDown event looks like this:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
TriggerKey(e.KeyCode, true);
}
Edit2:
I've tried removing the button from my form, and then both events trigger correctly. If I add it back in, the keyDown event stops working again. Why is the button interfering when the keypreview property is set?
KeyPreview is a VB6 compatibility feature, it isn't "native" Winforms. And it has a problem that exactly matches your issue. There are other Form methods that get a sniff at the keystroke first, before the code that looks at KeyPreview gets a chance to run and fire the KeyDown event. And they eat the navigation keystrokes first. Like the cursor keys that you are trying to see as well as the Tab key. This matches the VB6 behavior, it also couldn't see the cursor keys.
To stay ahead of that code, you'll need to override the ProcessDialogKey() method of the form. Like this:
protected override bool ProcessDialogKey(Keys keyData) {
switch (keyData) {
case Keys.Left:
//...
return true;
}
return base.ProcessDialogKey(keyData);
}
you're setting mUp on keyDown...? can you add all the related code context such as the mouse up event, also you may try to refresh, if you break does the even fire on key down?
Note that keyup is raised after keydown(if you want your mUp to remain true)
I saw in other similar posts that this could help
this.focus();
give it a try and let me know to keep looking for other ways
When a ContextMenuStrip is opened, if the user types the first letter of a possible selection - it's as if he clicked on it. I want to intercept that and get the character that he clicked.
The following code does that, but with hard-coding the possible character. I want a generic way to do this, either by disabling the automatic selection by key stroke (leaving only the mouse clicks) or some way to intercept the character.
The following simplified code assumes I want to have a winform's Text to be the character typed, and the ContextMenuStrip has one option which is "A".
public Form1()
{
InitializeComponent();
contextMenuStrip1.KeyDown += contextMenuStrip1_KeyDown;
}
private void button1_Click(object sender, EventArgs e)
{
contextMenuStrip1.Show();
}
void contextMenuStrip1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
if (e.KeyCode == Keys.A)
{
if (e.Shift) Text = "A";
else Text = "a";
}
}
Using the KeyPress event and checking e.KeyChar doesn't work because it doesn't get fired. (the "A" click-event gets fired instead.)
Using one of these: e.KeyCode, e.KeyData, or e.KeyValue doesn't work (without further hard-coding) because they accept a Shift as a Key.
As noted in the comment, you have to derive your own class from ContextMenuStrip so you can override the ProcessMnemonic() method.
Annotating this a bit, keyboard processing is very convoluted in Winforms. Shortcut keystrokes are processed very early, before they are dispatched to the control with the focus. Necessarily so, you would not want to implement the KeyDown event for every control so that you could make a shortcut keystroke work.
This works from the outside in and involves several protected methods, ProcessCmdKey, ProcessDialogChar and ProcessMnemonic. As well as OnKeyDown if the form's KeyPreview property is set, a VB6 compat feature. So the form gets a shot at it first, then it iterates controls from there, going from container to child controls.
The ToolStrip class (a base class for ContextMenuStrip) overrides the ProcessMnemonic() method to recognize key presses, mapping them to menu items. So in order to intercept this default processing, you have to override ProcessMnemonic() yourself to get a shot at the key press first.
Basically, I have a form with a custom control on it (and nothing else). The custom control is completely empty, and the form has KeyPreview set to true.
With this setup, I am not receiving any KeyDown events for any arrow keys or Tab. Every other key that I have on my keyboard works. I have KeyDown event handlers hooked up to everything that has such events, so I'm sure I'm not missing anything.
Also of note is that if I remove the (completely empty) custom control, I DO get the arrow key events.
What on earth is going on here?
EDIT:
I added this to both the form and the control, but I'm STILL not getting arrow keys:
protected override void WndProc(ref Message m) {
switch (m.Msg) {
case 0x100: //WM_KEYDOWN
//this is the control's version. In the form, it's this.Text
ParentForm.Text = ((Keys)m.WParam).ToString();
break;
}
base.WndProc(ref m);
}
I also checked with Spy++, and determined that the form itself is not getting any WM_KEYDOWN messages, they're all going to the control. However, that said, the control IS getting the arrow key WM_KEYDOWN messages. Sigh.
Edit 2: I've also updated the ZIP file with this version. Please look at it, if you want to help...
Edit 3:
I've figured this out, sort of. The form is eating the arrow keys, probably in an attempt to maintain focus amongst its children. This is proven by the fact that I DO get the events if the form is empty.
Anyway, if I add this code to the form, I start getting the events again:
public override bool PreProcessMessage(ref Message msg) {
switch (msg.Msg) {
case 0x100: //WM_KEYDOWN
return false;
}
return base.PreProcessMessage(ref msg);
}
When I override this, the form doesn't get a chance to do its dirty work, and so I get my KeyDown events as I expect. I assume that a side effect of this is that I can no longer use my keyboard to navigate the form (not a big deal in this case, as it's a game, and the entire purpose of this exercise is to implement keyboard navigation!)
The question still remains about how to disable this "properly", if there is a way...
I've done some extensive testing, and I've figured everything out. I wrote a blog post detailing the solution.
In short, you want to override the ProcessDialogKey method in the form:
protected override bool ProcessDialogKey(Keys keyData) {
return false;
}
This will cause the arrow keys (and tab) to be delivered as normal KeyDown events. HOWEVER! This will also cause the normal dialogue key functionality (using Tab to navigate controls, etc) to fail. If you want to retain that, but still get the KeyDown event, use this instead:
protected override bool ProcessDialogKey(Keys keyData) {
OnKeyDown(new KeyEventArgs(keyData));
return base.ProcessDialogKey(keyData);
}
This will deliver a KeyDown message, while still doing normal dialogue navigation.
If focus is your issue, and you can't get your user control to take a focus and keep it, a simple work-around solution would be to echo the event to your user control on the key event you are concerned about. Subscribe your forms keydown or keypress events and then have that event raise an event to your user control.
So essentially, Form1_KeyPress would Call UserControl1_KeyPress with the sender and event args from Form1_KeyPress e.g.
protected void Form1_KeyPress(object sender, KeyEventArgs e)
{
UserControl1_KeyPress(sender, e);
}
Otherwise, you may have to take the long route and override your WndProc events to get the functionality you desire.
I am switching several TextBoxes out for RichTextBoxes to gain some of the cool features.
I had my TextBoxes configured to AcceptReturn so that the enter key will create a new line, rather than leave the control. The RichTextBox does not seem to have this feature.
Is there a simple way to do this, or do I have to capture all keypresses and handle them individually?
Note: This issue occurs only when you set the "AcceptButton" property of the form.
Set the RichTextBox.AcceptsTab to true. For some reason this works for both tabs and the enter key. If you only want the enter keys then you will have to write custom code.
Since Carter pointed out that this only applies if AcceptButton is set, and the other solution suggests deriving the RichTextBox class, I found another simple solution. Just unset AcceptButton for the time that the/a RichTextBox has the focus. Here's a sample code:
private void RichText_Enter(object sender, EventArgs e)
{
AcceptButton = null;
}
private void RichText_Leave(object sender, EventArgs e)
{
AcceptButton = OKActionButton;
}
This assumes that you only have a single AcceptButton and that is unlikely to change. Otherwise you would have to copy some AcceptButton finding logic here or just backup the previous AcceptButton value before setting it to null.
This solution also has the side effect of removing the default border from the actual accept button, indicating to the user that pressing the Enter key now will not activate that button.
The solution is to override IsInputKey:
protected override bool IsInputKey(Keys keyData)
{
if (
(keyData & ~Keys.Modifiers) == Keys.Tab &&
(keyData & (Keys.Control | Keys.Alt)) == 0
)
return false;
return base.IsInputKey(keyData);
}
After setting AcceptsTab to true, you ensure that the RichTextBox processes both the tab and return key. With the IsInputKey implementation above, we ensure that the Tab and Shift+Tab key never reach the RichTextBox so they are used for navigation instead.
The above override must be pasted in a class derived from RichTextBox.
Just change Accept option in Richtextbox Property turn to "true" it will work like a magic