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

标签 c# windows

我想将另一个应用程序调到前台,但是,我只有窗口的部分名称。过去,我会连接到 EnumWindows API 并寻找我需要的东西。

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

最佳答案

这应该可以完成工作:

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

 }                                             
} 

关于c# - 如何通过部分标题名称设置前景窗口>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1002836/

相关文章:

c# - 无法从下拉列表中选择元素

c# - 设置不在线(IPEnabled 不正确)/电缆未连接的网络接口(interface)的 IP 地址?

windows - 在远程机器上使用 robot.createScreenCapture 获取黑色图像

c++ - Windows KMFD HelloWorld 驱动程序部署任务失败

c++ - 更改控制台颜色并保留 C++ 中的输出

c# - SqlDataReader 没有正确的列数

c# - C# 中的跨进程锁定

c# - 如何使用 WCF 服务暂时停止证书错误

windows - 无需锁定的优雅文件读取

windows - 调试器错误 193 拉撒路