Reputation: 145
I have a Form that is listening for the keyboard shortcut Ctrl+H using a KeyDown()
method.
When the shortcut is pressed, the form opens an 'about' form:
if (e.Control && e.KeyCode == Keys.H)
{
About about = new About();
about.ShowDialog();
}
Whenever I press Ctrl+H, it will effectively press the backspace button as well. If I have text selected in a textbox, it will delete the selection. If I am clicked into a textbox, it deletes the last character.
Create a new Windows Forms application using Visual Studio 2022.
Add a TextBox to Form1
, and make it multiline.
Create a second Form called Form2
. You don't need anything in that, just the form.
Add a KeyDown
event to Form1
.
In the Form1
constructor, add the following line:
KeyPreview = true;
Form1_KeyDown()
, add the following code:if (e.Control && e.KeyCode == Keys.H) {
Form2 other = new Form2();
other.ShowDialog();
}
I'm using Microsoft Visual Studio Community 2022 (64-bit) - Current Version 17.1.5
with Dotnet 6.0 (LTS)
.
I've looked through all of my code and done a fair amount of Googling. I followed the steps outlined above, and the same problem occurs, so I've isolated the problem to 2 lines:
Form2 other = new Form2();
other.ShowDialog();
The reason I add KeyPreview = true;
is so that the keyboard shortcuts still work if the user is clicked into the TextBox.
There are no error messages of any sort, just the undesired behavior of the backspace button being pressed when creating a new form.
I have found nothing on the web regarding this problem. If nobody can come up with a solution, I will report it to Microsoft as a bug.
Upvotes: 1
Views: 686
Reputation: 1153
The solution is to make sure that the Form
has KeyPreview
set to true
and add SupressKeyPress = true
to your code.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.H)
{
e.SuppressKeyPress = true;
// show dialog
}
}
Upvotes: 2
Reputation: 145
I just found this post that explains the solution.
How to disable a textbox keyboard shorcuts in c#?
For others who have this problem, here is the explanation.
Control+H is the ASCII code for backspace. To overcome the problem, set the textbox to readonly until the form is opened, to override the shortcut.
textBox1.ReadOnly = true;
Form2 other = new Form2();
other.ShowDialog();
textBox1.ReadOnly = false;
Hope this helps somebody!
~REMCodes
Upvotes: 1