日期:2014-05-17  浏览次数:21025 次

C#向一个窗口发送模拟按键的用法,自己的笔记贴

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Runtime.InteropServices;

namespace ConsoleApplication2
{
    class Program
    {
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string classname, string captionName);

        //[DllImport("user32.dll", EntryPoint = "FindWindowEx", CharSet = CharSet.Auto)]
        //private extern static IntPtr FindWindowEx(IntPtr parent, IntPtr child, string classname, string captionName);

        //[DllImport("user32.dll")]
        //static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);

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

        static void Main(string[] args)
        {
            
            IntPtr mwh1 = IntPtr.Zero;

            while (mwh1 == IntPtr.Zero)
            {
                Thread.Sleep(1000);
                mwh1 = FindWindow(null, "无标题 - 记事本");
            }


            SetForegroundWindow(mwh1);
            //发送字符串
            System.Windows.Forms.SendKeys.SendWait("username");
            //模拟tab键
            System.Windows.Forms.SendKeys.SendWait("{TAB}");
            //模拟ctrl+A全选
            System.Windows.Forms.SendKeys.SendWait("^a");
            //模拟回车键
            //System.Windows.Forms.SendKeys.SendWait("{ENTER}");
        }
    }
}