I have something along the lines of..
private UavControlForm()
{
InitializeComponent();
if (ControlFacade.CheckIfStkIsLaunched())
{
_control开发者_高级运维Facade = new ControlFacade();
SubscribeToStkQuit();
}
else
{
Thread tExitUavController = new Thread(ExitUavController);
tExitUavController.IsBackground = true;
tExitUavController.Start();
}
}
private void ExitUavController()
{
Thread.Sleep(500);
ForceCloseAtBeginning();
Application.Exit();
}
private void ForceCloseAtBeginning()
{
DialogResult dlgResult =
MessageBox.Show("STK application not running. UavController will now close.", "Closing...",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
The thread is used to ensure the WinForm is fully initialised before attempting the exit. This seems like bad practice to me... how can I better implement such functionality?
You should implement your own Main method for your application. Within the project settings, tell the application to use this method, instead of starting the Form.
Within this Main method, you would perform the check for whether the external application is running, and if so - then run the Form.
Example:
static void Main()
{
if (!ControlFacade.CheckIfStkIsLaunched())
{
DialogResult dlgResult =
MessageBox.Show("STK application not running. UavController will now close.", "Closing...",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Exit();
return;
}
Application.Run(new UavControlForm());
}
I would extract the logic of checking for whether STK application is running to outside of the form and only initialize the form if the application is running.
But if you're trying to ensure that the form fully initializes before it closes, then either override the form's closing event or hook onto it, and cancel the closing if the STK application is not running.
protected override void OnClosing(CancelEventArgs e) {
if (!ControlFacade.CheckIfStkIsLaunched()) {
e.Cancel = true;
}
base.OnClosing(e);
}
Why not just override the OnLoad method in the Form and then do the check?
精彩评论