How to bring my application window to front? For example whan my app needs attention.
This is for my personal program. I need that functionality.
This is what I got. But it's NOT working 100% times.
public void BringToFrontToEnterCaptha()
{
if (InvokeRequired)
{
Invoke(new Action(BringToFrontToEnterCaptha));
}
else
{
this.TopMost = true;
this.Focus();
this.BringToFront();
this.textBox1.Focus();
this.textBox1.Text = string.Empty;
System.Media.SystemSounds.Beep.Play();
}
}
public void BringToBackAfterEnterCaptha()
{
if (InvokeRequired)
{
Invoke(new Action(BringToBackAfterEnterCaptha));
}
else
{
this.TopMost = false;
}
}
And I call them from background worker.
BringToFrontToEnterCaptha();
while (!ready)
{
Thread.Sleep(100);
}
BringToBackAfterEnterCaptha();
Thread.Sleep(300);
And after pressing "Accept" button bool ready is set to true.
I works great but not always.
Here is a piece of code that worked for me
this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;
It always brings the desired window to the front of all the others.
this works:
if (WindowState == FormWindowState.Minimized)
WindowState = FormWindowState.Normal;
else
{
TopMost = true;
Focus();
BringToFront();
TopMost = false;
}
Use Form.Activate()
or Form.Focus()
methods.
I use SwitchToThisWindow to bring the application to the forefront as in this example:
static class Program
{
[DllImport("User32.dll", SetLastError = true)]
static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew;
int iP;
Process currentProcess = Process.GetCurrentProcess();
Mutex m = new Mutex(true, "XYZ", out createdNew);
if (!createdNew)
{
// app is already running...
Process[] proc = Process.GetProcessesByName("XYZ");
// switch to other process
for (iP = 0; iP < proc.Length; iP++)
{
if (proc[iP].Id != currentProcess.Id)
SwitchToThisWindow(proc[0].MainWindowHandle, true);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new form());
GC.KeepAlive(m);
}
Before stumbling onto this post, I came up with this solution - to toggle the TopMost property:
this.TopMost = true;
this.TopMost = false;
I have this code in my form's constructor, eg:
public MyForm()
{
//...
// Brint-to-front hack
this.TopMost = true;
this.TopMost = false;
//...
}
While I agree with everyone, this is no-nice behavior, here is code:
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
SetForegroundWindow(Handle.ToInt32());
Update
David is completely right, for completeness I include the list of conditions that must apply for this to work (+1 for David!):
Source: Stackoverflow.com