我在我的C#程序textBox中
我需要在程序启动时,焦点将放在textBox上
我在Form_Load上尝试这个:
MyTextBox.Focus();
Run Code Online (Sandbox Code Playgroud)
但它不会工作
V4V*_*tta 325
设置ActiveControl
表单的属性,你应该没问题.
this.ActiveControl = yourtextboxname;
Run Code Online (Sandbox Code Playgroud)
Nei*_*ght 14
你可以尝试:
根据文件:
如果控件的可选样式位在ControlStyles中设置为true,则Select方法将激活控件,它包含在另一个控件中,并且其所有父控件都可见并启用.
您可以通过检查MyTextBox.CanSelect属性来检查是否可以选择控件.
Dav*_*idG 13
如果尚未渲染,则无法将焦点设置为控件.Form.Load()在呈现控件之前发生.
转到表单的事件,然后双击"已显示"事件.在窗体的显示事件处理程序中调用control.Focus()方法.
private void myForm_Shown(object sender, EventArgs e)
{
// Call textbox's focus method
txtMyTextbox.Focus();
}
Run Code Online (Sandbox Code Playgroud)
之所以无法使其正常工作,是因为该Load
事件是在绘制或呈现表单之前调用的。
这就像告诉披萨店如何制作披萨,然后要求他们向您发送一张照片,说明披萨制作之前披萨上有多少意大利辣香肠。
using System;
using System.Windows.Forms;
namespace Testing
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
Load += TestForm_Load;
VisibleChanged += TestForm_VisibleChanged;
Shown += TestForm_Shown;
Show();
}
private void TestForm_Load(object sender, EventArgs e)
{
MessageBox.Show("This event is called before the form is rendered.");
}
private void TestForm_VisibleChanged(object sender, EventArgs e)
{
MessageBox.Show("This event is called before the form is rendered.");
}
private void TestForm_Shown(object sender, EventArgs e)
{
MessageBox.Show("This event is called after the form is rendered.");
txtFirstName.Focus();
}
}
}
Run Code Online (Sandbox Code Playgroud)