16

I have a problem with a program that loses focus. It's not my program. How can I write a second program to set focus to that window every 1-2 seconds? Is is possible to do that?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Endiss
  • 699
  • 2
  • 10
  • 23
  • Are you saying that you would want the focus to switch between your program and this other second program every seconds? Or in your application would would like to bring the other program to the front every 2 seconds (in case it has gone to the back again)? – Faraday Jun 05 '12 at 13:52
  • Is it a program(different program process) or ur child form? – Rajesh Subramanian Jun 05 '12 at 13:53
  • its diffrent program and i want my program to bring only it on focus ... – Endiss Jun 05 '12 at 14:08
  • Does this answer your question? [Correct way (in .NET) to switch the focus to another application](https://stackoverflow.com/questions/2315561/correct-way-in-net-to-switch-the-focus-to-another-application) – Wai Ha Lee Aug 11 '21 at 11:03

2 Answers2

27

You can use following Win32 API call if you want to focus some other program/process.

[DllImport("user32.dll")]
static extern bool SetForegroundWindow (IntPtr hWnd);

private void BringToFront(Process pTemp)
{
    SetForegroundWindow(pTemp.MainWindowHandle);
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Rajesh Subramanian
  • 6,400
  • 5
  • 29
  • 42
10

use spy++ or other ui tools to find the class name of the window you want to focus, say its: focusWindowClassName. Then add the below functions:

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

[System.Runtime.InteropServices.DllImport("User32.dll")]
 public static extern bool ShowWindow(IntPtr handle, int nCmdShow);

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

//Then:
// [Edit] Changed IntPrt to IntPtr
IntPtr hWnd = FindWindow("focusWindowClassName", null); // this gives you the handle of the window you need.

// then use this handle to bring the window to focus or forground(I guessed you wanted this).

// sometimes the window may be minimized and the setforground function cannot bring it to focus so:

/*use this ShowWindow(IntPtr handle, int nCmdShow);
*there are various values of nCmdShow 3, 5 ,9. What 9 does is: 
*Activates and displays the window. If the window is minimized or maximized, *the system restores it to its original size and position. An application *should specify this flag when restoring a minimized window */

ShowWindow(hWnd, 9); 
//The bring the application to focus
SetForegroundWindow(hWnd);

// you wanted to bring the application to focus every 2 or few second
// call other window as done above and recall this window again.
Community
  • 1
  • 1
Pradeep Bogati
  • 203
  • 2
  • 8