As a workaround for a problem, I think I have to handle KeyDown events to get the printable character the user actually typed.
KeyDown supplies me with a KeyEventArgs object with the properities KeyCode, KeyData, KeyValue, Modifiers, Alt, Shift, Control.
My first attempt was just to consider the KeyCode to be the ascii code, but KeyCode on my keyboard is 46, a period ("."), so I end up printing a period when the user types the delete key. So, I know my logic is inadequate.
(For those who are curious, the problem is that I have my own combobox in a DataGridView's control collection and somehow SOME characters I type don't produce the KeyPress and TextChanged ComboBox events. These letters include Q, $, %....
This code will reproduce the problem. Generate a Form App and replace the ctor with this code. Run it, and try typing the letter Q into the two comboxes.
public partial class Form1 : Form
{
ComboBox cmbInGrid;
ComboBox cmbNotInGrid;
DataGridView grid;
public Form1()
{
InitializeComponent();
grid = new DataGridView();
cmbInGrid = new ComboBox();
cmbNotInGrid = new ComboBox();
cmbInGrid.Items.Add("a");
cmbInGrid.Items.Add("b");
cmbNotInGrid.Items.Add("c");
cmbNotInGrid.Items.Add("d");
this.Controls.Add(cmbNotInGrid);
this.Controls.Add(grid);
grid.Location = new Point(0, 100);
this.grid.Controls.Add(cmbInGrid);
}
Many controls override the default key input events. For instance, a Panel won't respond to them by default at all. As for the case of simple controls, you could try:
protected override bool IsInputKey(Keys keyData) {
// This snippet informs .Net that arrow keys should be processed in the panel (which is strangely not standard).
switch (keyData & Keys.KeyCode) {
case Keys.Left:
return true;
case Keys.Right:
return true;
case Keys.Up:
return true;
case Keys.Down:
return true;
}
return base.IsInputKey(keyData);
}
The IsInputKey function tells your program what keys to receive events from. There is a chance you'll get weird behaviour if you override keys that clearly have special functions, but experiment a little and see for yourself what works and what doesn't.
Now, for more advanced controls like a DataGridView or ComboBox, keyhandling can be even more complicated. The following resource should give you a few pointers about how to go about your problem:
http://www.dotnet247.com/247reference/msgs/29/148332.aspx
Or this resource might perhaps solve your problem:
http://dotnetperls.com/previewkeydown
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With