我正在尝试用C#学习GUI编程,我对C#中TextBox的默认代码有以下问题:
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 WindowsFormsApplication34
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// Textbox programming goes here
}
}
}
现在,当我想尝试使用类似于此代码的TexBox编程时稍微不同的东西
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 WindowsFormsApplication20
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
//
// Detect the KeyEventArg's key enumerated constant.
//
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("You pressed enter! Good job!");
}
else if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("You pressed escape! What's wrong?");
}
}
}
}
我无法运行代码,因为TextBox的状态是
textBox1_KeyDown
而不是默认的
textBox1_TextChanged
现在我的问题是,如何将TextBox事件处理程序从默认处理程序更改为另一个?
答案 0 :(得分:6)
KeyDown
和TextChanged
是不同的事件。
不是双击文本框以输入事件代码,而是选择属性中的事件选项卡,然后双击要为其编写代码的事件。
答案 1 :(得分:1)
我认为你想要寻找的是OnPreviewKeyDown事件......它告诉你接下来会发生什么。如果您想绕过它的活动,可以设置" Handled"财产到真。
protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
{
var ue = e.OriginalSource as FrameworkElement;
if (e.Key == Key.Enter)
{
MessageBox.Show("You pressed enter! Good job!");
e.Handled = true; // to tell event stack you've already taken care of this condition
}
else if (e.KeyCode == Keys.Escape)
MessageBox.Show("You pressed escape! What's wrong?");
}