我有以下代码,允许用户写入可执行文件(即 notepad.exe),然后单击开始按钮它将启动该进程。
但是,如何让文本框接受 Enter/Return 键呢?我输入了
AcceptsReturn=true
但它没有做任何事情。我还在 Visual Studio 中设置了属性 Accept Return = True
- 仍然没有。
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;
using System.Diagnostics;
namespace process_list
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
Process process = new Process();
process.StartInfo.FileName = text;
process.Start();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.AcceptsReturn = true;
}
}
}
AcceptButton
设置为您的按钮。那么您不需要 AcceptsReturn
,因为 Enter 会自动触发该按钮。
public Form1()
{
InitializeComponent();
this.AcceptButton = button1;
}
将
KeyDown
事件方法添加到 textBox1
并在方法内部执行此操作
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button1_Click(sender, e);
}