如何通过部分标题名称设置前景窗口>

时间:2009-06-16 17:17:44

标签: c# windows

我想将另一个应用程序带到前台,但是,我只有一个部分名称的窗口。回到当天,我会加入EnumWindows API并寻找我需要的东西。

有没有办法在C#中做得更好?一个例子就是很棒。

1 个答案:

答案 0 :(得分:3)

这应该做的工作:

[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);    

 }                                             
}