C# 获取键盘输入数字的值
C# 代码如下:
/// <summary>
/// 重载ProcessCmdKey事件
/// </summary>
/// <param name="msg"></param>
/// <param name="keyData"></param>
/// <returns></returns>
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
int index = dgvBasesList.CurrentCell.RowIndex;
string text = Clipboard.GetText();
EventArgs e = new EventArgs();
if (keyData == Keys.Enter)
{
this.btnOK_Click(this, e);
}
else if (keyData == Keys.Down)
{
if (index < dgvBasesList.Rows.Count - 1)
{
// dgvBasesList.Rows[index + 1].Selected =true ;
dgvBasesList.CurrentCell = dgvBasesList[0, index + 1];
txtNo.Text = (dgvBasesList.CurrentRow.Index + 1).ToString();
}
}
else if (keyData == Keys.Up)
{
if (index > 0)
{
dgvBasesList.CurrentCell = dgvBasesList[0, index - 1];
txtNo.Text = (dgvBasesList.CurrentRow.Index + 1).ToString();
}
}
else if ((keyData >= Keys.D0 && keyData <= Keys.D9) || (keyData >= Keys.NumPad0 && keyData <= Keys.NumPad9))
{
string num = KeyCodeToStr(keyData);
string num1 = num;
int no = Int32.Parse(txtNo.Text.ToString() + num);
if (no > dgvBasesList.Rows.Count - 1)
{
if (Int32.Parse(num) > dgvBasesList.Rows.Count)
{
dgvBasesList.CurrentCell = dgvBasesList[0, dgvBasesList.Rows.Count - 1];
txtNo.Text = (dgvBasesList.Rows.Count - 1).ToString();
}
else if (Int32.Parse(num) > 0)
{
dgvBasesList.CurrentCell = dgvBasesList[0, Int32.Parse(num) - 1];
txtNo.Text = num.ToString();
}
}
else
{
dgvBasesList.CurrentCell = dgvBasesList[0, no - 1];
txtNo.Text = no.ToString();
}
}
return true;}
[DllImport("user32.dll")]
static extern int MapVirtualKey(uint uCode, uint uMapType);private static char KeyCodeToChar(Keys k)
{
int nonVirtualKey = MapVirtualKey((uint)k, 2);
char mappedChar = Convert.ToChar(nonVirtualKey);
return mappedChar;
}
public static string KeyCodeToStr(Keys k)
{
char mappedChar = KeyCodeToChar(k);
string str = mappedChar.ToString();
if (Char.IsWhiteSpace(mappedChar) || string.IsNullOrEmpty(str) || mappedChar == '\r' || mappedChar == '\n' || mappedChar == KeyCodeToChar(Keys.F1))
{
return k.ToString();
}
else
{
return str + "";
}
}
2011-02-19