7
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;


namespace TextSendKeys
{
    class Program
    {
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        static void Main(string[] args)
        {
            Process[] processes = Process.GetProcessesByName("game");
            Process game1 = processes[0];


            IntPtr p = game1.MainWindowHandle;

            ShowWindow(p,1);
            SendKeys.SendWait("{DOWN}");
            Thread.Sleep(1000);
            SendKeys.SendWait("{DOWN}");



        }
    }
}

That program is suposed to send twice DOWN button in a game window. It only works, when my window is minimized (it's activating the window and doing it's job). If my window is activated (not minimized), nothin happens. How to solve that?

Thanks! :)

Patryk
  • 3,042
  • 11
  • 41
  • 83
  • Can you do without a window? Try creating a console program if you don't really need a window. – Sandeep Datta Jan 21 '12 at 13:53
  • while using through console application getting error like this "the name 'SendKeys' does not exist in the current context. ". how can i resolve this error. @Autodidact – chandu komati May 25 '20 at 15:01

1 Answers1

12

Try using the SetForegroundWindow Win32 API call, instead of ShowWindow, to activate the game window. (Signature from pinvoke.net.)

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

static void Main(string[] args)
{
    Process[] processes = Process.GetProcessesByName("game");
    Process game1 = processes[0];

    IntPtr p = game1.MainWindowHandle;

    SetForegroundWindow(p);
    SendKeys.SendWait("{DOWN}");
    Thread.Sleep(1000);
    SendKeys.SendWait("{DOWN}");
}
Douglas
  • 53,759
  • 13
  • 140
  • 188