如果字符串使用C#与数组不匹配

时间:2017-09-09 14:01:53

标签: c# arrays

我有这个代码来查找Windows标题,如果它们在数组中则关闭它们。如果窗口/标题在那里,这很好用,如果没有,它只是坐着(因为我没有告诉它做任何事情)..而这就是我被困住的地方(并希望得到一些帮助)。 / p>

static void Main(string[] args)
{
    Console.Title = "Windows Title";

    int i = 0;   // While Loop counter
    System.Console.WriteLine("Starting to look for pop-up windows....\n");

    while (i <= 9)        // while i is equal to , or less than 9......
    {
        string[] errorArray = { "Apple", "Banana", "pear", "plum", "pineapple", "0", "1", 
                                  "2", "3", "4", "5", "6", "7", "8,", "9" };

        foreach (KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
        {
            string title = window.Value;

            if (errorArray.Any(title.Equals))
            {
                i++;                                                       
                System.Console.WriteLine("\nFound {0} of 9 error messages\n", i);// 
                int iHandle = FindWindow(null, title);
                SendMessage(iHandle, WM_SYSCOMMAND, SC_CLOSE, 0);
                System.Console.WriteLine("{0} pop up closed\n", title);
                Thread.Sleep(5000);
            }
            else
            {
               //wait for a 60 seconds , then 
            }
        }
    }
    Environment.Exit(0);
}

我被困在ELSE部分要做什么。 该应用程序将作为计划任务运行。 如果它运行,并且没有打开的窗口标题与数组匹配,那么我希望它关闭。 如果窗口标题存在,那么它(并且确实)以增量i(直到i = 9)启动已经存在的代码。

任何人都可以帮助我如何让它等待吗?

感谢

1 个答案:

答案 0 :(得分:0)

你可以这样做:

    bool finished=false;
    do
    {
    finished=false;

foreach (KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
            {
                string title = window.Value;

                if (errorArray.Any(title.Equals))
                {
                    i++;                                                       
                    System.Console.WriteLine("\nFound {0} of 9 error messages\n", i);// 
                    int iHandle = FindWindow(null, title);
                    SendMessage(iHandle, WM_SYSCOMMAND, SC_CLOSE, 0);
                    System.Console.WriteLine("{0} pop up closed\n", title);
                    finished=true;
                }
                else
                {
                   thread.Sleep(60000);
                   //wait for a 60 seconds , then 
                }


            }
} while (finished==false)

如果以下条件返回false,主线程将进入休眠状态60秒:

if (errorArray.Any(title.Equals))

它将继续循环,直到条件返回true。

关注你的评论。如果您希望该方法以异步方式运行(不清楚您的问题),请查看此处:https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap