pikausp
pikausp

Reputation: 1192

Winforms - Display a form from different thread and sync z-order with the main form

I need to show a form upon CollectionChanged event that is fired on winform Timer thread. However, the new dialog is not bound to the main window, meaning, the main window is not brought to front when the dialog gets focused and vice versa. Also, the new window doesn't "inherit" the application icon ( can be seen when in alt-tab view )

using( var form = new CommunicationForm() { Owner = (MainForm)Parent.Parent } ){
    form.ShowDialog();
}

I assumed this may be caused by the code not being executed on the main thread or Ower not being assigned ( when displaying the form in button ( which is not direct child of the main window ) click it works as expected ) so I tried running it on main thread and assigning the parent window

this.Invoke( (MethodInvoker)delegate {
    using( var form = new CommunicationForm() { Owner = (MainForm)Parent.Parent } ) {
        form.ShowDialog();
    }
} );

this was a bit better, but still after bringing the application to front and closing the dialog, the main form is pushed back ( z-order wise ). Which I assume is caused by the main window not being on the top at the time of dialog being showen.

The question is, am I still doing it wrong? And if not, how can I get the main form to stay in front after the dialog is closed?

Upvotes: 0

Views: 438

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

You should pass your MainForm instance reference to the Form.ShowDialog() method when you are showing the CommunicationForm.

Upvotes: 1

Related Questions