Note that there are some explanatory texts on larger screens.

plurals
  1. POModification of Utility Method to Support Multi-Threading
    text
    copied!<p>I have been given a application to multi-thread and this has been done. All message boxes in this application are correctly called by a single <code>static</code> method in a utility class. This method is:</p> <pre><code>public static void ErrMsg(String strMsg, Exception ex = null) { ... if (ex == null) MessageBox.Show(strMsg, "MyApp", MessageBoxButtons.OK, MessageBoxIcon.Warning); ... } </code></pre> <p>Clearly this does not provide the <code>IWin32Window</code> owner and this is now causing me a problem when I invoke an error message from a background thread-pool thread using this method. The problem is a known one of the message box showing behind my main form. See:</p> <ol> <li><a href="https://stackoverflow.com/questions/3104661/popping-a-messagebox-for-the-main-app-with-backgroundworker-in-wpf">Popping a MessageBox for the main app with Backgroundworker in WPF</a></li> </ol> <p>et al. I could pass in the <code>SynchronisationContext</code> of the current thread to <code>ErrMsg</code> and do </p> <pre><code>synchronizationContext.Send(callback =&gt; MessageBox.Show("Some error message for the user"), null); </code></pre> <p>But there are 700+ calls to this method, the majority of which are on the UI thread and do not cause a problem. My question is: <strong>how can I amend the <code>ErrMsg</code> method so that my message box appears in front reguardless of the current <code>SynchronisationContex</code> and without having to ammend all 700+ calls to the method?</strong></p> <p>Thanks for your time.</p> <hr> <p><strong>Edit.</strong> @Dmitry's idea was great. However, if the active form does not have focus or is an MdiChild form then the <code>Form.ActiveForm</code> will return null. To get around this I use <code>Application.OpenForms.Cast&lt;Form&gt;().Last()</code> to get the last active form, beit MdiChild or whatever. The code is now...</p> <pre><code>Form activeForm = Application.OpenForms.Cast&lt;Form&gt;().Last(); if (ex == null) { activeForm.Invoke(new ShowErrMsg(text =&gt; MessageBox.Show(activeForm, text, "UserCost", MessageBoxButtons.OK, MessageBoxIcon.Warning)), strMsg); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload