nivolas
nivolas

Reputation: 317

Sending a keypress to the active window that doesn't handle Windows message in C#

When I am detecting a pixel with a given color, I want to send the Key "k". The problem is that even though the window is active, wit the following code it sends me an exception : SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method. The Sendwait method doesn't seem to press the key fast enough (but at least it gives no exception). I don't really care if the required solution is "dirty", it's a poc I'll use once

static void Main(string[] args)
    {
        string ligne;
        string previousligne = string.Empty;
        int compteur = 0;        
            while (true)
            {
                Color pixColor = Win32.GetPixelColor(System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y);
                ligne = pixColor.Name;                    
                if (previousligne != ligne)
                {
                    if (ligne == "ffcecefe")
                    {
                        SendKeys.Send("k");
                    }

                    Console.WriteLine(ligne);
                    System.IO.File.AppendAllText(@"C:\Users\Public\WriteLines.txt", "-----" + DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond + " = " + ligne);                        
                    previousligne = ligne;
                    compteur++;
                    if (compteur % 10 == 0)
                    {
                        System.IO.File.AppendAllText(@"C:\Users\Public\WriteLines.txt", "---------" + compteur);
                        Console.WriteLine("---------" + compteur);
                    }
                }
            }
    }

If you know Final Fantasy X, I'm trying to automate the process of avoiding the lightning bolts : video

I could just cheat to get the ingame result (or do it the legit way) and it would have already been done, but if I can learn a bit more of C# instead it would be better.

Upvotes: 2

Views: 9913

Answers (1)

theB
theB

Reputation: 6738

The console window (i.e. your running process) is the active window which SendKeys is sending data to. Since the console doesn't have a message loop, there is nowhere for the message to be received at, and it's lost. You would need to activate the target window with something like SetActiveWindow().

See also How do I send key strokes to a window without having to activate it using Windows API?

Upvotes: 1

Related Questions