ShowDialog 不阻止执行代码但阻止 UI

use*_*026 1 .net c# visual-studio winforms

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

letturalog can3 = new letturalog();
                    (new System.Threading.Thread(() => {
                        can3.ShowDialog();
                    })).Start();
Run Code Online (Sandbox Code Playgroud)

此模式不会阻塞代码和 UI。

所以我想知道你是否能做到

Ian*_*oyd 6

如果你不想阻止代码,那么你想调用.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;
Run Code Online (Sandbox Code Playgroud)

事实上,这就是全部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);
   } 
}
Run Code Online (Sandbox Code Playgroud)

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

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;
   } 
}
Run Code Online (Sandbox Code Playgroud)