C# 中组合框的 KeyPress 事件
KeyPress event on combobox in C#
我在桌面应用程序中有一个组合框,我想给它一个 KeyPress 动作侦听器
这是我的代码
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
int selectedIndex = combobox.SelectedIndex;
if (selectedIndex >= 0)
{
switch (selectedIndex)
{
//.......
};
this.Close();
}
}
}
现在我需要将它添加到组合框中,我尝试类似
this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);
但它不起作用。
您需要向事件添加处理程序,而不是一些参数。 (它甚至可以编译吗?)
而不是
this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);
尝试
this.combobox.KeyDown += new KeyEventHandler(this.comboBox1_KeyDown);
KeyEventHandler
在 System.Windows.Forms 命名空间中。
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.KeyDown += comboBox1_KeyDown;
}
除了编译问题,我认为你应该用 SelectedIndexChanged 处理 SelectedIndex
事件,因为 KeyDown
如果在 SelectedIndex 更改之前触发。
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
您的代码有问题 connecting between The Event Handler Method and The Event
this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);
在上面的代码行中,您使用 KeyEventArgs
作为事件处理程序方法。但它不是事件处理程序方法。
相反,您应该使用KeyEventHandler
,这是相应的事件处理程序方法来处理事件。
EventArgs
EventArgs
表示包含事件数据的 class 的基础 class,并提供用于不包含事件数据的事件的值。
包含事件数据的 EventArgs
的实例被事件处理程序方法用于根据需要执行操作。
KeyEventHandler
KeyEventHandler
是处理控件的 KeyUp
或 KeyDown
事件的方法。
与KeyPress
事件类似,有KeyPressEventHandler
方法。
因此您应该将代码更改为:
this.comboBox.KeyDown +=
new System.Windows.Forms.KeyEventHandler(this.ComboBox_KeyDown);
我在桌面应用程序中有一个组合框,我想给它一个 KeyPress 动作侦听器
这是我的代码
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
int selectedIndex = combobox.SelectedIndex;
if (selectedIndex >= 0)
{
switch (selectedIndex)
{
//.......
};
this.Close();
}
}
}
现在我需要将它添加到组合框中,我尝试类似
this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);
但它不起作用。
您需要向事件添加处理程序,而不是一些参数。 (它甚至可以编译吗?)
而不是
this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);
尝试
this.combobox.KeyDown += new KeyEventHandler(this.comboBox1_KeyDown);
KeyEventHandler
在 System.Windows.Forms 命名空间中。
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.KeyDown += comboBox1_KeyDown;
}
除了编译问题,我认为你应该用 SelectedIndexChanged 处理 SelectedIndex 事件,因为 KeyDown 如果在 SelectedIndex 更改之前触发。
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
您的代码有问题 connecting between The Event Handler Method and The Event
this.combobox.KeyDown += new KeyEventArgs(this.comboBox1_KeyDown);
在上面的代码行中,您使用 KeyEventArgs
作为事件处理程序方法。但它不是事件处理程序方法。
相反,您应该使用KeyEventHandler
,这是相应的事件处理程序方法来处理事件。
EventArgs
EventArgs
表示包含事件数据的 class 的基础 class,并提供用于不包含事件数据的事件的值。
包含事件数据的 EventArgs
的实例被事件处理程序方法用于根据需要执行操作。
KeyEventHandler
KeyEventHandler
是处理控件的 KeyUp
或 KeyDown
事件的方法。
与KeyPress
事件类似,有KeyPressEventHandler
方法。
因此您应该将代码更改为:
this.comboBox.KeyDown +=
new System.Windows.Forms.KeyEventHandler(this.ComboBox_KeyDown);