查找外部窗口标题
Posted
技术标签:
【中文标题】查找外部窗口标题【英文标题】:Find external window Title 【发布时间】:2014-07-26 05:31:20 【问题描述】:我得到了这个代码:
using System.Runtime.InteropServices;
[DllImportAttribute("User32.dll")]
private static extern int FindWindow(String ClassName, String WindowName);
[DllImport("User32")]
private static extern int ShowWindow(int hWnd, int nCmdShow);
private const int SW_HIDE = 0;
int hWnd = FindWindow(null, Microsoft Excel - Book1);
if (hWnd > 0)
ShowWindow(hWnd, SW_HIDE);
但有时我会用 OpenOffice.org 打开 Book1.. 我的问题是,我如何 SW_HIDE 不同的窗口标题?
如果 Microsoft Excel - Book1 标题存在
如果 Book1 - OpenOffice.org Calc 标题存在
也许可以找到窗口标题部分“Book1”
非常感谢!
【问题讨论】:
您需要枚举所有窗口并检查它们的标题(首先请参阅here)。你到底想通过隐藏窗户来实现什么?也许有更好的方法。 FindWindow() 相当粗糙,在这种情况下完全没用。你会领先于 Process.MainWindowHandle。当您使用可以创建许多窗口的应用程序执行此操作时,您实际上要隐藏哪个窗口在很大程度上仍然是一个随机事件,这些窗口都不像“主”窗口那样特别。不要这样做。 【参考方案1】:使用以下代码获取所有打开的窗口的列表。
[DllImport("user32.dll")]
static extern bool EnumWindows(EnumDelegate lpfn, IntPtr lParam);
然后编写委托函数如下:
public string[] win_List = new string[50];
int i = 0;
public bool lpfn(IntPtr hWnd, int lParam)
StringBuilder stbrTitle = new StringBuilder(255);
int titleLength = GetWindowText(hWnd, stbrTitle, stbrTitle.Capacity + 1);
string strTitle = stbrTitle.ToString();
if (IsWindowVisible(hWnd) && string.IsNullOrEmpty(strTitle) == false)
win_List[i++] = strTitle;
return true;
public string[] GetWinList()
EnumDelegate del_fun = new EnumDelegate(lpfn);
EnumWindows(del_fun, IntPtr.Zero);
return win_List;
【讨论】:
以上是关于查找外部窗口标题的主要内容,如果未能解决你的问题,请参考以下文章