Hey,
I make a project of a chess board connected through serial port to the pc. Chess board sends commands like 'g1f3'. I'd like to make a clicker app which works in the background and clicks the move I made on the real board. I stucked at recognizing chess client window title. I've got this code:
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        while (true)
        {
            backgroundWorker1.ReportProgress(0);
            System.Threading.Thread.Sleep(1000);
        }
    }
    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        windowName = GetActiveWindowTitle();
        for (int i = 0; i <= windowName.Length - 3; i++)
        {
            if (windowName[i] == 'v' && windowName[i + 1] == 's' && windowName[i + 2] == '.')
            {
                textBox1.Text = "Game active";
                break;
            }
            else
                textBox1.Text = "Game not recognized";
        }
    }
Chess client names the window like: "xxxxx vs. xxxxx". This runs "almost" fine. "Almost" because sometimes (if app windows changed fast or randomly after even 1 switch delayed in time) it throws:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an invocation.
Anyone could give me some hint how to handle this?
Edit: I got the code for GetActiveWindowTitle() from here: How do I get the title of the current active window using c#?
It throws null sometimes, but why is that? 
     
    