C# Winform 设置焦点控件的两种方式和注意事项

一、方法
//设置本窗体的活动控件为某个控件
this.ActiveControl = this.button2;

//调用Focus方法设置某个控件获取焦点
this.button2.Focus();

二、注意事项
1、在窗体实例化——加载——绘制——显示完毕四个过程中使用两种方法设置效果有区别,具体如下:

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//this.ActiveControl = this.button2;//生效
//this.button2.Focus();//不生效(在构造函数里使用,不生效)
}

private void Form1_Load(object sender, EventArgs e)
{
//this.ActiveControl = this.button2;//生效
//this.button2.Focus(); //不生效(在加载事件里使用,不生效)
}

private void Form1_Shown(object sender, EventArgs e)
{
//this.ActiveControl = this.button2;//生效
//this.button2.Focus(); //生效(在显示事件里使用,生效)
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
//this.ActiveControl = this.button2;//生效
this.button2.Focus(); //生效(在绘制函数里使用,生效)
}
}
}

posted @ 2024-06-15 10:33  花GE  阅读(13)  评论(0编辑  收藏  举报