简体   繁体   中英

How to freeze the outlook window on VSTO?

I have a problem with MessageBox dialog, normally, the MessageBox will freeze and block the windows, and show on the top of the current windows till user click the messagebox button, but I got the the messagebox cannot block and freeze the current windows on VSTO ribbon button

private async void BtnTest_Click(object sender, RibbonControlEventArgs e)
{
    MessageBox.Show("before");

    var task = await DoSomethingAsync();

    MessageBox.Show("after");
}

private async Task<bool> DoSomethingAsync()
{
    await Task.Delay(1000);
    return true;
}

The first MessageBox can freeze the windows, but the second cannot not be, after investigate I found it caused by the await, when I await till DoSomethingAsync finished, the second MessageBox will normally freeze and block the current windows

private void BtnTest_Click(object sender, RibbonControlEventArgs e)
{
    MessageBox.Show("before");

    var task = DoSomethingAsync();
    task.Wait();
    var result = task.Result;

    MessageBox.Show("after");
}

but I don't want block the Office Outlook Robbin UI, so I want to execute the DoSomethingAsync asynchronous, anyone know how to fix it?

You can run a secondary thread using the Thread.Start method instead:

using System.Threading;

Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();

where the WorkThreadFunction method should look like the following one:

public void WorkThreadFunction()
{
  try
  {
     // do any background work
  }
  catch (Exception ex)
  {
     // log errors
  }
}

Also I'd recommend specifying the parent window handle to the Show method. You can cast an instance of the Inspector or Explorer class to the IOleWindow interface which provides the GetWindow function which retrieves a handle to one of the windows participating in in-place activation.

Then you can create an instance of the IWin32Window interface which can be passed to the Show method:

public class WindowWrapper : System.Windows.Forms.IWin32Window
{
   public WindowWrapper(IntPtr handle)
   {
       _hwnd = handle;
   }

   public IntPtr Handle
   {
       get { return _hwnd; }
   }

   private IntPtr _hwnd;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM