C# 如何将正则表达式与FindWindow一起使用?
我最终尝试写一些东西来检查特定窗口是否存在,并在它存在时将其设置为活动。 我能够使用FindWindow查找windows的文字名称C# 如何将正则表达式与FindWindow一起使用?,c#,regex,winforms,setfocus,findwindow,C#,Regex,Winforms,Setfocus,Findwindow,我最终尝试写一些东西来检查特定窗口是否存在,并在它存在时将其设置为活动。 我能够使用FindWindow查找windows的文字名称 int hWnd = FindWindow(null, "121226-000377 - company - Oracle RightNow CX Cloud Service"); if (hWnd > 0) //If found { SetForegroundWindow(h
int hWnd = FindWindow(null, "121226-000377 - company - Oracle RightNow CX Cloud Service");
if (hWnd > 0) //If found
{
SetForegroundWindow(hWnd); //Activate it
}
else
{
MessageBox.Show("Window Not Found!");
}
标题前面的数字会发生变化,并且不会两次相同,因此我尝试使用正则表达式来查找是否有任何活动窗口具有如上所示的名称结构,但数字可能会发生变化。我有一个用于此的常规表达式,但我不知道如何实现它。我试过:
int hWnd = FindWindow(null, @"^\d+-\d+\s.*?RightNow CX");
if (hWnd > 0) //If found
{
SetForegroundWindow(hWnd); //Activate it
}
else
{
MessageBox.Show("Window Not Found!");
}
但它不断失败。那么,如何使用FindWindow/setforegroughindow命令,同时让它们使用正则表达式进行检查呢
更新~~~~
我选择了一个最好的答案,但下面是我如何让它工作的实际代码,以防有人感兴趣
protected static bool EnumTheWindows(IntPtr hWnd, IntPtr lParam)
{
int size = GetWindowTextLength(hWnd);
if (size++ > 0 && IsWindowVisible(hWnd))
{
StringBuilder sb = new StringBuilder(size);
GetWindowText(hWnd, sb, size);
Match match = Regex.Match(sb.ToString(), @"^\d+-\d+\s.*?RightNow CX",
RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
ActivateRNT(sb.ToString());
}
else
{
//this gets triggered for every single failure
}
//do nothing
}
return true;
}
private static void ActivateRNT(string rnt)
{
//Find the window, using the CORRECT Window Title, for example, Notepad
int hWnd = FindWindow(null, rnt);
if (hWnd > 0) //If found
{
SetForegroundWindow(hWnd); //Activate it
}
else
{
MessageBox.Show("Window Not Found!");
}
}
我仍然需要弄清楚如何在EnumWindows方法中进行测试,以便在所需窗口不存在时抛出警报,但我稍后会担心这一点。我猜这就是您要寻找的,尽管我不能100%确定在C中如何使用它,因为您需要回调
编辑:得到一些代码,包括一个示例回调。
编辑2:链接的[MSDN sample][3]有更多关于为什么/如何这样做的详细信息。我认为没有内置的函数/方法/API用于搜索具有正则表达式模式的窗口。一种方法是枚举窗口,然后使用正则表达式比较回调函数中的窗口文本。如果您知道所搜索窗口的进程名称,可以尝试以下操作:
Process[] processes = Process.GetProcessesByName("notepad");
foreach (Process p in processes)
{
IntPtr pFoundWindow = p.MainWindowHandle;
SetForegroundWindow(pFoundWindow);
}
我使用EnumWindows检查所有活动窗口,如链接中所述,然后对照我的正则表达式进行检查,当其中一个通过正则表达式测试时,我将其按名称传递给FindWindow,然后将其设置为活动窗口。有关我的解决方案,请参阅修订的OP。