I have a winforms app, and I need to access the Handle property of a main form, inside a Backgroundworker thread.
I have made a thread safe method that calls the main form with InvokeRequired. My question is - why do I still get "InvalidOperationException cross-thread operation not valid" error, even when calling this thread safe method like this:
ProcessStartInfo psi = new ProcessStartInfo(file);
psi.ErrorDialogParentHandle = Utils.GetMainAppFormThreadSafe().Handle;
And below is the code of the thread safe method (my main app form is called Updater):
/// <summary>
/// delegate used to retrieve the main app form
/// </summary>
/// <returns></returns>
private delegate Updater delegateGetMainForm();
/// <summary>
/// gets the mainform thread safe, to avoid cross-thread exception
/// </summary>
/// <returns></returns>
public static Updater GetMainAppFormThreadSafe()
{
Updater updaterObj = null;
if (GetMainAppForm().InvokeRequired)
{
delegateGetMainForm deleg = new delegateGetMainForm(GetMainAppForm);
updaterObj = GetMainAppForm().Invoke(deleg) as Updater;
}
else
{
updaterObj = GetMainAppForm();
}
return updaterObj;
}
/// <summary>
/// retrieves the main form of the application
/// </summary>
/// <returns></returns>
public static Updater GetMainAppForm()
{
Updater mainForm = System.Windows.Forms.Application.OpenForms[Utils.AppName] as Updater;
return mainForm;
}
Am I doing smth wrong? Thank you in advance.
LATER EDIT: I'll post the reason why I need the handle in the first place, perhaps there is another solution/approach. In My Backgroundworker thread I need to install multiple programs in a loop, and I start a process for each installer. However I need to ask for elevation so that this operation can work for standard users as well, not only admins. In short, I am trying to follow the tutorial here