方法
-
//设置本窗体的活动控件为某个控件
this.ActiveControl = this.button2; -
//调用Focus方法设置某个控件获取焦点
this.button2.Focus();
注意事项
在窗体实例化——加载——绘制——显示完毕四个过程中使用两种方法设置效果有区别,具体如下:
- 构造方法中:
this.ActiveControl = this.button2;//生效
this.button2.Focus(); //不生效
- Load(加载)事件中:
this.ActiveControl = this.button2;//生效
this.button2.Focus(); //不生效
- Paint(绘制)事件中:
this.ActiveControl = this.button2;//生效
this.button2.Focus(); //生效
- Shown(显示完毕)事件中:
this.ActiveControl = this.button2;//生效
this.button2.Focus(); //生效
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(); //生效
}
}
}