tags:

views:

207

answers:

1

I want to bring another application into the foreground, however, I only have a partial name of the window. Back in the day, I'd hook into the EnumWindows API and look for what I needed.

Is there a way to do this better in C#? An example would be great.

+1  A: 

This should do the job:

[DllImport("user32.dll", EntryPoint="SystemParametersInfo")]  
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni);  

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

[DllImport("User32.dll", EntryPoint="ShowWindowAsync")]  
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);  
private const int WS_SHOWNORMAL = 1;  
private const int SW_SHOWMAXIMIZED = 3;

[DllImport("user32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);

private struct WINDOWPLACEMENT
{
  public int length;
  public int flags;
  public int showCmd;
  public System.Drawing.Point ptMinPosition;
  public System.Drawing.Point ptMaxPosition;
  public System.Drawing.Rectangle rcNormalPosition;
}

Process[] processes = Process.GetProcesses();  
foreach(Process p in processes){              
 if(p.MainWindowTitle.Contains("nice_title")){
  WINDOWPLACEMENT wp = new WINDOWPLACEMENT();
  placement.length = Marshal.SizeOf(placement);
  GetWindowPlacement(p.MainWindowHandle, ref placement);

  int proposedPlacement = wp.showCmd;

  if (wp.showCmd == SW_SHOWMINIMIZED)
    proposedPlacement = SW_SHOWMAXIMIZED;

  SystemParametersInfo( (uint) 0x2001, 0, 0, 0x0002 | 0x0001);  
  ShowWindowAsync(p.MainWindowHandle, proposedPlacement);  
  SetForegroundWindow(p.MainWindowHandle);  
  SystemParametersInfo( (uint) 0x2001, 200000, 200000, 0x0002 | 0x0001);    

 }                                             
}
merkuro
Sweet. And to bring the window into the foreground?
AngryHacker
Just updated the code. It should now be a fully working example. Any problems so far?
merkuro
That's great, however, there is one small flaw. If the window is maximized or minimized, the code restores it. I think, it'd be cool if the code restored the window only if it were minimized.
AngryHacker
Untested, however something like this probably is going to make you happy :)
merkuro
Perfect. It was good to jump into the bad old world of Windows APIs.
AngryHacker