I'm getting some strange behaviour in the start-up of a Windows app and wondered if anyone could throw any light on what is happening and how to get around it.
The problem is with the start-up of the app - it should show a splash screen then a login form. The code for this is:
[STAThread]
static void Main()
{
Application.ThreadException += Application_ThreadException;
MainForm mainForm = null;开发者_Python百科
Thread splashThread = new Thread(ShowSplash);
try
{
// set up app
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Splash screen
Splash splash = new Splash();
splashThread.Start(splash);
// enable logging
log4net.Config.XmlConfigurator.Configure();
// Create main form
mainForm = new MainForm();
// kill splash
HideForm(splash);
splashThread.Abort();
}
catch (Exception e)
{
splashThread.Abort();
MessageBox.Show(e.Message, "An exception occurred: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(0);
}
// start
Login login = new Login();
login.Show();
if (!mainForm.IsDisposed)
{
Application.Run(mainForm);
}
}
static void ShowSplash(object splash)
{
if (!(splash is Splash))
throw new ArgumentException("Splash screen is of wrong type.");
Splash splashForm = (Splash) splash;
splashForm.ShowDialog();
}
// Thread safe hide form
private delegate void HideFormCallback(Form form);
private static void HideForm(Form form)
{
if (form == null || form.IsDisposed)
return;
if (form.InvokeRequired)
{
HideFormCallback d = HideForm;
form.Invoke(d, new object[] { form });
}
else
{
form.Hide();
}
}
So, we're starting up a new thread with the splash screen, setting up the rest of the app in the meantime, then killing the splash screen just before showing the login form.
The problem I'm having is that the login form doesn't have focus when the app starts. The splash screen pops up and goes away as expected. The login form pops up in front of any open windows but doesn't have focus - the folder containing the executable (that I double-clicked to launch) still has focus even when it's behind the login form.
If I comment out all the lines to do with the splash screen, the login form has focus when it appears.
My guess would be that the focus reverts back to the executable folder when the splash screen is hidden but I don't know why the login form doesn't get focus when it launches.
Calling .Focus() on the login form returns null so doesn't work.
Neither form have TopMost or such set on them.
If anyone has any suggestions for what's going on, it would be much appreciated.
This is what I've ended up doing as a somewhat hacky fix:
void LoginView_Shown(object sender, EventArgs e)
{
SetForegroundWindow(Handle);
this.BringToFront();
Activate();
}
[DllImport("user32")]
public static extern int SetForegroundWindow(IntPtr hwnd);
精彩评论