Как установить окно переднего плана по частичному названию заголовка> - PullRequest
1 голос
/ 16 июня 2009

Я хочу вывести другое приложение на первый план, однако у меня есть только частичное имя окна. В свое время я подключался к API EnumWindows и искал то, что мне было нужно.

Есть ли способ сделать это лучше в C #? Пример был бы великолепен.

1 Ответ

3 голосов
/ 16 июня 2009

Это должно сделать работу:

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

 }                                             
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...