I created a windows form application (using windows vista, MS visual studio 2008). This form only has a button and a textbox.

I need this form not to lose focus. for example when the form is on the screen, the user can click something that is behind the form, then the form will lose focus. So is there any way to programatically achieve this?

The form should always be on top (i have coded this using the topmost property), but yet i need the form to be focussed.

Another approach where we could code this as follows; When the form loses focus we could popup a message box (with Yes or No), when he clicks yes the Form will get back its focus.

Anyway i am clueless as in how to achieve this. can someone Help me

Recommended Answers

All 4 Replies

Its been a while sinced I used windows forms, but Im sure there is a LoseFocus event or something similar. In that event, just reset your focus using your window handle.

Edit: Here is a list of events available. http://msdn.microsoft.com/en-us/library/system.windows.forms.form_events.aspx

There is a Leave event. This triggers when the window loses focus. You would register this event for your main window and inside the event, reset focus to your program.

Edit #2: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx

Its been a while sinced I used windows forms, but Im sure there is a LoseFocus event or something similar. In that event, just reset your focus using your window handle.

Edit: Here is a list of events available. http://msdn.microsoft.com/en-us/library/system.windows.forms.form_events.aspx

There is a Leave event. This triggers when the window loses focus. You would register this event for your main window and inside the event, reset focus to your program.

Edit #2: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx

Ok i looked at Deactivate , seems promising, but how do i integrate it to my code.
i pasted the following code in Form.cs

private void Form1_Deactivate(Object sender, EventArgs e) {

   MessageBox.Show("You are in the Form.Deactivate event.");

}

but how does the Program knows if to execute this method ? Any clue ?

You have to register it. I assume you are using Visual studio as an aid to build it instead of programming it? If so, there is an event's list which can be found in the form properties window. In it, find the event and double click it and it will automatically register the event for you.

Edit: As for keeping the focus on the form, simply call this.Focus();. This will not keep the form from going behind other windows though.

Perhaps a look at this code snippet will shine a light.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.