[英]How to capture Enter key in a ListBox control?
我在互聯網上閱讀過文章,但我想這里缺少一些東西。 我嘗試遵循此SO問題的答案,但未發生任何反應。
每當我按下Enter / Return鍵時,我都想觸發usePort_Click方法。 另外,當我嘗試從ports_Keydown方法調用它時,我也不知道該如何解決usePort_Click的EventArgs參數。
注意: ports是一個ListBox控件。
private void usePort_Click(object sender, EventArgs e)
{
try
{
port = new SerialPort((string)ports.SelectedItem, 9600);
portUsedLabel.Text = (string)ports.SelectedItem;
String buffer = "";
String tellArduino = "food"; // test value
port.Open();
port.WriteLine(tellArduino);
for (int x = 0; x < tellArduino.Length; x++)
{
buffer += port.ReadLine();
}
ports.Items.Add(buffer);
port.Close();
}
catch { //stuff }
}
private void ports_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//code here
}
}
一個好的解決方案是將要執行的代碼移到一個單獨的方法中(我稱其為someStuff
,用更好的名稱替換名稱),然后從兩個事件處理程序中調用該方法:
private void usePort_Click(object sender, EventArgs e)
{
someStuff();
}
private void ports_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
someStuff();
}
}
private void someStuff()
{
try
{
port = new SerialPort((string)ports.SelectedItem, 9600);
portUsedLabel.Text = (string)ports.SelectedItem;
String buffer = "";
String tellArduino = "food"; // test value
port.Open();
port.WriteLine(tellArduino);
for (int x = 0; x < tellArduino.Length; x++)
{
buffer += port.ReadLine();
}
ports.Items.Add(buffer);
port.Close();
}
catch { //stuff }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.