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.