Somesh Dhal
Somesh Dhal

Reputation: 47

How do I bring a Windows form to the front in c#?

In my application when the user clicks on a label to open a form the form opens in the background.I mean it does not come to the front but is rather placed on taskbar. once the user cancels that instance of form and again clicks on the label,the form opens in foreground.Following portion of code does the specific work.

        if (DataFormDlg.Instance.InvokeRequired)
        {
            DataFormDlg.Instance.BeginInvoke(
                new ShowDataFormDelegate(ShowDataForm), pageId, timeout);
            return;
        }

        DataFormDlg.Instance.CurrentPageId = pageId;
        DataFormDlg.Instance.Timeout = timeout;

        if (!DataFormDlg.Instance.Visible)
            DataFormDlg.Instance.ShowDialog();
        else
            DataFormDlg.Instance.Focus();

Here the DataFormDlg is derived from windows form.

Upvotes: 0

Views: 133

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112352

Pass the current form as owner to the ShowDialog method. The dialog form can then never get behind the first form, even if the user clicks on the first form.

Another consequence is that the second form closes automatically when the owner form closes. This is especially useful when the second form is opened with Show instead of ShowDialog.

DataFormDlg.Instance.ShowDialog(this);

using this overloaded version:

public DialogResult ShowDialog(IWin32Window owner)

Upvotes: 1

Related Questions