maartenvdv
maartenvdv

Reputation: 177

How to run 2 forms without a messagebox on form 1 freezing form 2

On my first form I have a button that starts a second form. The second form start a RDP. everyting works fine but when I get a messagebox-message on form 1, I can't acces my second form untill I close the messagebox. How can I run the 2 forms apart from each other?

Upvotes: 0

Views: 193

Answers (4)

mgigirey
mgigirey

Reputation: 1113

You can call the native MessageBox:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int MessageBoxW(IntPtr hWnd, String lpText, String lpCaption, uint uType);

The first parameter is the parent handle, if you pass IntPtr.Zero the MessageBox will be parent-less. Made available an example https://github.com/mgigirey/MessageBoxWrapper/tree/master.

Upvotes: 0

Pavel Vladov
Pavel Vladov

Reputation: 4837

If you want to show a non modal (modeless) message to the user, you should create a form and use its Show method, instead of showing a message box. The following simple method creates and shows a form that looks like a message box:

public static Form ShowNonModalMessageBox(string title, string text)
{
    Form form = new Form();
    form.FormBorderStyle = FormBorderStyle.FixedDialog;
    form.MinimizeBox = false;
    form.MaximizeBox = false;
    form.Size = new Size(200, 100);
    form.StartPosition = FormStartPosition.CenterScreen;
    form.Text = title;

    form.SuspendLayout();

    Label label = new Label();
    label.Text = text;
    label.Dock = DockStyle.Fill;
    form.Controls.Add(label);

    Button okButton = new Button();
    okButton.Text = "OK";
    okButton.Dock = DockStyle.Bottom;
    okButton.Click += delegate(object sender, EventArgs e)
    {
        form.DialogResult = DialogResult.OK;
        form.Close();
    };
    form.Controls.Add(okButton);

    form.ResumeLayout();

    form.Show();
    return form;
}

You can then use this method like this to show a non-modal message to the user:

Form messageBox = ShowNonModalMessageBox("Title", "This is the message.");
messageBox.FormClosed += messageBox_FormClosed;

private void messageBox_FormClosed(object sender, FormClosedEventArgs e)
{
    MessageBox.Show("Form closed with result: " + ((Form)sender).DialogResult.ToString());
}

Upvotes: 1

Marc
Marc

Reputation: 3959

Maybe you are using ShowDialog() instead of Show(), which displays your form as modal Dialog.

Upvotes: 0

Adrian Nasui
Adrian Nasui

Reputation: 1095

You should start the forms with the Show() method instead of ShowDialog().

Upvotes: 0

Related Questions