odkken odkken - 1 month ago 5
C# Question

Accessing GUI window created by a Caliburn.Micro application on a background thread?

I've got a caliburn.micro WPF application, and I'm launching it from F# with a call to this function:

public void LaunchGUI()
{
if (_guiWindow == null)
{
var windowThread = new Thread(() =>
{
try
{
// Create our context, and install it:
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));

AppBootstrapper.Initialize();
var app = new App();
app.InitializeComponent();


//guiWindow = app.MainWindow;
//// When the window closes, shut down the dispatcher
//guiWindow.Closed += (s, e) =>
// Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
//guiWindow.Closed += (s, e) =>
// guiWindow = null;
//guiWindow.WindowState = WindowState.Minimized;
//guiWindow.Show();
//guiWindow.WindowState = WindowState.Normal;
//guiWindow.Activate();
// Start the Dispatcher Processing
Dispatcher.Run();
}
catch (Exception e)
{
LogMessage("error in gui thread: " + e);
//guiWindow.Close();
//guiWindow = null;
}

});
windowThread.SetApartmentState(ApartmentState.STA);
windowThread.IsBackground = true;
windowThread.Start();
}
else
{
_guiWindow.WindowState = WindowState.Minimized;
_guiWindow.Show();
_guiWindow.WindowState = WindowState.Normal;
_guiWindow.Activate();
}
}
}


The issue is I need to have a reference to the main window so I can keep track of whether it's still open, etc., but it is always null (hence the commented code). Note this works fine when running a "normal" MVVM app, and initializing it in a similar way:

public void ShowGui()
{
if (guiWindow == null)
{
var windowThread = new Thread(() =>
{
try
{
// Create our context, and install it:
SynchronizationContext.SetSynchronizationContext(
new DispatcherSynchronizationContext(
Dispatcher.CurrentDispatcher));

guiWindow = new MainWindow();
// When the window closes, shut down the dispatcher
guiWindow.Closed += (s, e) =>
Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
guiWindow.Closed += (s, e) =>
guiWindow = null;
guiWindow.WindowState = WindowState.Minimized;
guiWindow.Show();
guiWindow.WindowState = WindowState.Normal;
guiWindow.Activate();

// Start the Dispatcher Processing
Dispatcher.Run();
}
catch (Exception)
{
try
{
guiWindow.Close();
}
catch (Exception)
{

throw;
}
guiWindow = null;
}

});
windowThread.SetApartmentState(ApartmentState.STA);
windowThread.IsBackground = true;
windowThread.Start();
}
else
{
guiWindow.WindowState = WindowState.Minimized;
guiWindow.Show();
guiWindow.WindowState = WindowState.Normal;
guiWindow.Activate();
}
}


My question is how do I get access to the main window created?

Answer

// you get get the application main windows like this:

var _guiWindow = Application.Current.MainWindow as MainWindow;