ShowDialog没有阻止执行代码但阻止UI

时间:2016-04-23 09:41:20

标签: c# .net winforms visual-studio

当我使用ShowDialog()显示表单时,它会阻止UI和代码,但我只需要阻止UI而不是代码。

letturalog can3 = new letturalog();
                    (new System.Threading.Thread(() => {
                        can3.ShowDialog();
                    })).Start();

此模式不会阻止代码和用户界面。

所以我想知道你能否做到

1 个答案:

答案 0 :(得分:3)

如果您不想阻止代码,则需要致电.Show

换句话说,你想要:

can3.Show(this);
this.Enabled = false; //disable the form so the UI is blocked

//...do our stuff now that code is not blocked while the UI is blocked

//All done processing; unblock the UI:
this.Enabled = true;

实际上,这就是ShowDialog所做的一切:禁用表单,然后重新启用它。在伪代码中:

void ShowDialog(IWindowHandle Owner)
{ 
   this.Show(Owner);

   try
   {
      //Disable the owner form 
      EnableWindow(Owner, false);

      repeat
      {
         Application.DoEvents();
      }
      until (this.DialogResult != DialogResult.None);
   }
   finally
   {
      //Re-enable the UI!
      EnableWindow(owner, true);
   } 
}

你可以窃取所有这些概念,并用你想要的任何东西替换胆量:

void DoStuffWithTheThing()
{ 
   can3.Show();

   try
   {
      //Disable the owner form 
      this.Enabled = false;

      //todo: Solve the P=NP conjecture
   }
   finally
   {
      //Re-enable the UI!
      this.Enabled = true;
   } 
}