Artem Kachanovskyi
Artem Kachanovskyi

Reputation: 1969

WinForms Button Click event and similar events depend on focus

I have the next situation:

The problem is, when I click on a Button on another TabPage, in TabPage.Enter event handler I take focus to my hidden TextBox, and it seems like Button click event doesn't have enough time to be processed. When I put timer and handle TabPage.Enter event after 100 ms, the Button click event seems to be fired well. Same thing happens to all the controls: CheckBox doesn't get checked, RadioButton too. I wouldn't like to use timer, as that is not a stable solution.

Any ideas how could I make TabPage to process all mouse events before I take focus to hidden TextBox? I tried to use Application.DoEvents(), but that didn't help.

Upvotes: 0

Views: 703

Answers (1)

LightBulb
LightBulb

Reputation: 964

You are using a wrong event for a wrong control for what you are trying to do.

Enter event for TabPage is going to be fired when that page becomes an active control of the current form which might not happen under certain conditions. Instead, you need to use Selecting or Selected event of TabControl, depending on whether you want to cancel switching to a different tab or not (see TabControlCancelEventArgs parameter of Selecting event). In your case, Selecting event would be more appropriate since it won't allow switching to a selected tab until event is complete (unless you're doing an asynchronous request to the server). Additionally, you may no longer need to use the hidden TextBox.

UPDATE

Regarding comments to OP, when you have 2 (or more) TabControls on a form and you want to get notified when you press a button in any tab of a different TabControl, you can use Enter event for TabControl. Use a global variable to store which TabControl was activated in the Enter event and then send server request for a currently active tab of that activate TabControl.

If this doesn't work for your scenario, then you need to carefully examine your workflow and see if it can be improved in relation to what you want to accomplish.

Upvotes: 1

Related Questions