button的触发事件Key_Down和KeyPress出现问题
这三个是效果图
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool flag = false;
public Form1()
{
InitializeComponent();
button1.KeyPress+=new KeyPressEventHandler(button_KeyPress);
button2.KeyPress+=new KeyPressEventHandler(button_KeyPress);
}
private void button1_Click(object sender, EventArgs e)
{
if (flag == false)
{
label1.Text = "Good Night";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (flag == false)
{
label1.Text = "Good Afternoon";
}
}
private void button_KeyPress(object sender,KeyPressEventArgs e)
{
flag = false;
if (32 == e.KeyChar)
{
flag = true;
}
}
}
}
这个是源码 button
[解决办法]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Button的空格回车响应
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void btn_Night_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
this.label1.Text = "Night:按下空格";
//e.Handled = true; //再此时按下回车无效
//e.Handled = false; //再此时按下回车无效
//e.SuppressKeyPress = true;
}
if (e.KeyCode == Keys.Enter)
{
this.label1.Text = "Night:按下回车";
//MessageBox.Show("回车");
//e.Handled = true;
}
else
{
this.label1.Text = "????";
}
}
private void btn_Night_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
this.label1.Text = "Up_空格";
//e.Handled = true;
}
else if (e.KeyCode == Keys.Enter)
{
this.label1.Text = "Up_回车";
//e.Handled = true;
}
}
private void btn_Night_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 32)
{
this.label1.Text = "Press_空格";
}
else if (e.KeyChar == 44)
{
this.label1.Text = "Press_回车";
}
}
}
}
在KeyDown和KeyPress 中没有截获 回车,KeyUp中 都截获了
[解决办法]
看19楼。
[解决办法]
private void FormMain_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 32)
{
this.Text = "窗口KeyPress 空格";
e.Handled = false;
}
}
看这段,窗口 响应 KeyPress事件处理, e.Handled = false,按键消息会传递给button继续处理,如果设置为true,则消息 不会 在 传递给button的KeyPress处理了。
[解决办法]
确实有点蛋疼,回车键无法被keypress获取响应到,试了下只有keyup事件是能够响应到回车事件的
要不就这样,多绑定一个KEYUP的?
public Form1()
{
InitializeComponent();
button1.KeyUp += new KeyEventHandler(button_KeyUp);
button2.KeyUp += new KeyEventHandler(button_KeyUp);
button1.KeyPress += new KeyPressEventHandler(button_KeyPress);
button2.KeyPress += new KeyPressEventHandler(button_KeyPress);
}
private void button_KeyUp(object sender, KeyEventArgs e)
{
flag = false;
if (32 == e.KeyValue)
{
flag = true;
}
else
{
label2.Text = e.KeyValue.ToString();
}
}