C# 使用Win32 API

这段代码展示了如何使用C#进行自动化操作,包括模拟鼠标点击、键盘输入和窗口操作。通过DllImport导入user32.dll库,实现了移动鼠标、模拟鼠标按键、查找和设置窗口最前等功能,可用于自动化测试或脚本编写。
摘要由CSDN通过智能技术生成

引用:

using System.Runtime.InteropServices;

using WinForm = System.Windows.Forms;

鼠标键盘方法定义:

//--------------------------

//鼠标

//----------------------
// [System.Runtime.InteropServices.DllImport("User32")]
// private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)\]
static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

//移动鼠标
const int MOUSEEVENTF_MOVE = 0x0001;

//模拟鼠标左键按下
const int MOUSEEVENTF_LEFTDOWN = 0x0002;

//模拟鼠标左键抬起
const int MOUSEEVENTF_LEFTUP = 0x0004;

//模拟鼠标右键按下
const int MOUSEEVENTF_RIGHTDOWN = 0x0008;

//模拟鼠标右键抬起
const int MOUSEEVENTF\_RIGHTUP = 0x0010;

//模拟鼠标中键按下
const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;

//模拟鼠标中键抬起
const int MOUSEEVENTF_MIDDLEUP = 0x0040;

//标示是否采用绝对坐标
const int MOUSEEVENTF_ABSOLUTE = 0x8000;

public const int MouseLeftDown = 0x2;
public const int MouseLeftUp = 0x4;

//---------------------------
//键盘
//---------------------------

/// <summary>
/// 寻找窗口
/// </summary>
/// <param name="strClass"></param>
/// <param name="strWindow"></param>
/// <returns></returns>

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr FindWindow(string strClass, string strWindow);

/// <summary>
/// 将窗口放置在最上层
/// </summary>
/// <param name="hWnd"></param>
/// <returns></returns>
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);

\[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)\]

static extern int GetWindowTextLength(IntPtr hWnd);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, string lpString, int cch);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr EnumChildWindows(IntPtr hWndParent, CallBack lpEnumFunc, int lParam);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int SetCursorPos(int x, int y);

public delegate bool CallBack(IntPtr hwnd, int lParam);
public struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

public static int nCount;

public static bool EnumWindowsProc(IntPtr h, int lparam)
{

    string strText = new string((char)0, 255);
    //RECT hRect = new RECT();
    nCount = nCount + 1;
    int Ret = 0;
    Ret = GetWindowTextLength(h);
    string sSave = new string((char)9, Ret);
    GetWindowText(h, sSave, Ret + 1);
    if (sSave.IndexOf("2", 0) > -1)
    {

        SetCursorPos(200, 160);
        return false;
    }
    return true;
}

测试输入英文字母:

private void btnKeyInput\_Click(object sender, RoutedEventArgs e)
        {

            //英文输入
            this.rtxt1.Focus();
            //for (int i = 65; i < 91; i++) //A-Z
            //{
            //    char Letter = (char)i;
            //    WinForm.SendKeys.SendWait(Letter.ToString());
            //    //SendKeys.Send(Letter.ToString());
            //    System.Threading.Thread.Sleep(100);
            //    WinForm.SendKeys.Flush();
            //}

            for (int i = 97; i < 123; i++)//a-z
            {

                char Letter = (char)i;
                WinForm.SendKeys.SendWait(Letter.ToString());
                System.Threading.Thread.Sleep(100);
                WinForm.SendKeys.Flush();
                System.Threading.Thread.Sleep(100);
            }
        }

测试将字符串输入到文本文件:

private async Task ShowMessage(string msg)
        {
            await this.rtxt1.Dispatcher.BeginInvoke(new Action(() =>
            {
                rtxt1.AppendText($"{msg}\r\n");
                rtxt1.ScrollToEnd();
            }));
        }

        private async void btnMouse_Click(object sender, RoutedEventArgs e)
        {

            IntPtr h;

            string strName = "键盘输入.txt - 记事本";

            h = FindWindow(null, strName);

            await ShowMessage($"窗口找到:{h}");

            if (h.ToInt32() != 0)

            {
                SetForegroundWindow(h);
                await ShowMessage($"窗口设置为顶层窗口");

                SetCursorPos(300, 600);
                await ShowMessage($"移到鼠标位置(300,600)");

                mouse_event(MouseLeftDown | MouseLeftUp, 0, 0, 0, 0);
                await ShowMessage($"单击");
                await ShowMessage($@"输入字符串- D:\零基础学SQL.pdf");

                WinForm.SendKeys.SendWait(@"D:\零基础学SQL.pdf");
                System.Threading.Thread.Sleep(200);
                SetCursorPos(750, 670);
                mouse_event(MouseLeftDown | MouseLeftUp, 0, 0, 0, 0);

            }
        }

效果如下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值