winfrom点击按钮修改数据_点击一个winform应用程序按钮后,你如何将焦点返回到上次使用的控制?...

I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:

The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.

I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:

public partial class Form1 : Form

{

Control _lastEnteredControl;

private void textBox_Enter(object sender, EventArgs e)

{

_lastEnteredControl = (Control)sender;

}

private void button1_Click(object sender, EventArgs e)

{

MessageBox.Show("Do something here");

_lastEnteredControl.Focus();

}

}

So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?

解决方案

For a bit of 'simplicity' maybe try.

public Form1()

{

InitializeComponent();

foreach (Control ctrl in Controls)

{

if (ctrl is TextBox)

{

ctrl.Enter += delegate(object sender, EventArgs e)

{

_lastEnteredControl = (Control)sender;

};

}

}

}

then you don't have to worry about decorating each textbox manually (or forgetting about one too).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值