C# // SendKeys.SendWait works only when process'es window is minimzed

£可爱£侵袭症+ 提交于 2019-11-27 18:50:18

问题


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! :)


回答1:


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}");
}


来源:https://stackoverflow.com/questions/8953399/c-sharp-sendkeys-sendwait-works-only-when-processes-window-is-minimzed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!