开发者

Show form that showDialog from mainForm won't block it, but closing mainForm will close it

how yo show a form which needs to run synchronously. I tried running application.run from开发者_开发技巧 a queueworker of a threadpool- but I had some invalid handles sometime. tried using a regular thread but then when main form closes it doesn't close this- and I don't really like the idea of killing the thread on_formclosing. if I use form.show it's fine besides that fact that any showdialog from the main form will block also this. What's the best way to handle this?


This is something you really should not fix. Keeping a form enabled while a dialog is displayed is risky. The user could start code from that form that shouldn't run while a dialog is active. Like displaying another dialog.

But you can with a trick and doing it carefully. The ShowDialog() call iterates all open forms and disables them. You could re-enable one by P/Invoking the EnableWindow() API function. The trick is to do so while the dialog is displayed, Control.BeginInvoke() can do this.

This is best explained with an example. It needs three forms and a button on the main form, all with their default names. Form2 is kept non-modal while the dialog is displayed. You may need to move it so it isn't hidden underneath the forms.

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      button1.Click += new EventHandler(button1_Click);
    }
    private Form2 mNonModal;
    void button1_Click(object sender, EventArgs e) {
      this.BeginInvoke(new MethodInvoker(makeNonModal));
      new Form3().ShowDialog(this);
    }
    void makeNonModal() {
      if (mNonModal != null) EnableWindow(mNonModal.Handle, true);
    }
    protected override void OnLoad(EventArgs e) {
      mNonModal = new Form2();
      mNonModal.FormClosed += (s, ea) => mNonModal = null;
      mNonModal.Show();
    }
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern void EnableWindow(IntPtr hWnd, bool enable);
  }


Probably it is the most simple to make the dialog non-modal, i.e. use Show() instead of ShowDialog(). Make the dialog a member of your main form and check in the main form's close event whether the dialog is open and close it if necessary.


You can just set IsBackground property of you thread to true, then you background thread will close when all foreground threads closed. You can read about background and foreground threads on msdn.


Try to use Show() instead of ShowDialog(). And also, create the object of your form class, for example MyForm^ theForm = gcnew MyForm();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜