C# - 循环 foreach 直到 true

标签 c# loops foreach while-loop msdn

C# 新手。但由于工作原因,我不得不“边学边学”。

过去 2 天我一直在为我的代码苦苦挣扎,我尽可能多地阅读这里的问题和 MSDN 上的文章,但我认为它们让我更加困惑。

我使用我的代码启动应用程序 A。应用 A 启动应用 B(我无法启动应用 B,我超出了)。
我想用我的代码做的是在应用程序 B 的 MainWindowTitle 可用时隐藏窗口。

到目前为止,我只能通过 Thread.Sleep(xxx) 完成此操作;在您看到下面的代码之前。 我想避免使用计时器。

我想做的是循环下面的代码,直到它为真。

When app A launches app B, it takes a few seconds for the MainWindowTitle to become available. But the code runs so fast that it's not available yet and the code is done.

IntPtr hWnd = IntPtr.Zero;
foreach (Process procList in Process.GetProcess())
{
    if (procList.MainWindowTitle.Contains("SAP Logon"))
    {
        hWnd = procList.MainWindowHandle;
    }
}
ShowWindow(hWnd, 0);

该代码只有在我在它前面加上类似的内容时才有效:

Thread.Sleep(10000);

在整个代码块之前。它起作用的唯一原因是 b/c 它允许足够的时间让窗口打开并包含我正在寻找的标题。

我试过 while 循环。

  • Outside the 'foreach'
  • Outside the 'if'
  • Around the 'foreach' (that locked up the system really quickly...) hah!
  • Around the 'if'

我觉得下面的其中一个应该起作用,但它不起作用,或者我完全搞砸了。

while (!procList.MainWindowTitle.Contains("SAP Logon")) { } // ! at the beginning OR
while (procList.MainWindowTitle.Contains("SAP Logon") == null) { } // equaling null OR
while (procList.MainWindowTitle.Contains("SAP Logon") < 0) { } // etc., etc.,
while (procList.MainWindowTitle.DOESNOTContain("SAP Logon")) { } // I know this is wrong but it almost seems like what I need...

有人有什么建议吗?我的大脑正在炒鸡蛋,这是我完成此应用程序所需的最后一点。 如果我唯一的选择是 Thread.Sleep(),那就这样吧,但我宁愿不使用它。 最后一件事:我必须以 .net 2.0 为目标。

谢谢!

最佳答案

您使用 while 循环的想法应该可行。你可以尝试这样的事情:

IntPtr hWnd = IntPtr.Zero;
bool isFound = false;
while(!isFound)
{
  foreach (Process procList in Process.GetProcess())
  {
    if (procList.MainWindowTitle.Contains("SAP Logon"))
    {
        isFound = true;
        hWnd = procList.MainWindowHandle;
    }
  }
  Thread.Sleep(100); // You may or may not want this
}
ShowWindow(hWnd, 0);

关于C# - 循环 foreach 直到 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20112369/

相关文章:

c# - 通过构建器模式使用 List<T> - c#

c# - 将 Azure Blob 与 Azure 网站连接

c - 如何垂直打印该字符串

javascript - 使用脚本应用程序从 Google Sheet 中的单元格中提取日期

php - foreach 循环结果插入数据库

c# - VS11 上的 Windows Workflow Foundation 教程

c# - 在两台计算机之间进行 .NET 远程处理时出现套接字错误

loops - ansible:如何遍历所有已注册的结果?

c# - 在新对象声明中使用 foreach

javascript - array.forEach 的 thisArg 没有按预期引用