尝试实现“进入”;事件处理程序到教科书
本文关键字:事件处理 程序 教科书 实现 进入 | 更新日期: 2023-09-27 18:04:24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using Microsoft.VisualBasic;
namespace HelloWorld
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string filePathTEST = "";
public MainWindow()
{
InitializeComponent();
// Clearing text event handlers
textBox1.GotFocus += textBox1_GotFocus;
// Enter event handlers for textboxes
textBox1.KeyDown += new System.Windows.Input.KeyEventHandler(textBox1_KeyDown);
}
static void textBox1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//enter key is down
}
}
当我尝试运行上述代码时,我得到的错误如下:
不能隐式转换类型"System.Windows.Forms。KeyEventHandler"System.Windows.Input.KeyEventHandler"
然后我尝试将代码更改为System.Windows.Input,然后我得到以下内容:
错误1"System.Windows.Input"。KeyEventArgs'不包含定义'KeyCode'并且没有扩展方法'KeyCode'接受"System.Windows.Input"类型的第一个参数。KeyEventArgs’可能是找到(您是否缺少using指令或程序集引用?)
我这样做的目的是当我在文本框上按回车键时,我想把文本框中的文本填充到一个特定的文本文件中,但我不知道该怎么做
编译器认为你的意思是使用'System.Windows.Forms '。KeyEventHandler'由于您添加的命名空间:System.Windows.Forms
.
删除这一行,你的代码应该可以工作了:
using System.Windows.Forms;
其次,您应该使用Key
而不是KeyCode
,因为这是WPF的变体:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
//
}
}
您遇到了相当混乱的Windows客户端开发状态。窗体是WinForms库的一部分,它是。net 1.0附带的原始UI框架。你正在使用的项目是用WPF (Windows Presentation Framework)编写的,WPF是。net 3中开始发布的新库。有很多重叠的地方,但这两个库是不同的。
你想要的类是System.Windows.Input.KeyEventArgs。如果你在MSDN上找到这个类的文档,你会看到它实际上没有KeyCode属性。但是,它有一个Key属性,它应该做你想做的。
我将把实际查找和阅读MSDN文档留给读者作为练习。: -)