新文章 网摘 文章 随笔 日记

C#用外挂模拟键盘输入

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    /// <summary>
    /// C#用外挂模拟键盘输入
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        private void BtnSend_Click(object sender, EventArgs e)
        {
            var processes = Process.GetProcessesByName("notepad++");
           
            foreach (Process proc in processes)
            {
                if (proc.MainWindowTitle != string.Empty)
                {
                    IntPtr handle = proc.MainWindowHandle;
                    SetForegroundWindow(handle);
                    ShowWindow(handle, 3);
                    //SendKeys.Send("123456");
                    //SendKeys.Send("{ENTER}");
                    //SendKeys.Send("567890");
                    //SendKeys.Send("{ENTER}");

                    Send(null, null);
                }
            }

        }

        private void Send(Dictionary<string, string> dict, Dictionary<int, string> configs)
        {

             dict = new Dictionary<string, string>()
            {
                {"carton","carton12345679" },
                {"sn","sn12345679" },
                {"pallet","pallet12345679" },
                {"boxno","boxno12345679" }
            };

            configs = new Dictionary<int, string>()
            {
                { 4,"pallet"},
                { 1,"carton"},
                { 2,"sn"},
                { 3,"boxno"},
            };

            var sort = configs.OrderBy(r => r.Key);
            foreach (var config in sort)
            {
                SendKeys.Send(dict[config.Value]);
                SendKeys.Send("\r\n");
            }
        }
    }
}

 可以使用json传入数据和发送顺序的配置,例如:

cofigs:

{
  "4": "pallet",
  "1": "carton",
  "2": "sn",
  "3": "boxno"
}

data:

{
    "carton": "carton12345679",
    "sn": "sn12345679",
    "pallet": "pallet12345679",
    "boxno": "boxno12345679"
}

然后通过反序列化的方式把它们赋值给字典dictionary,然后执行发送。

 

参考文章:https://www.cnblogs.com/makesense/p/6215732.html

posted @ 2023-04-26 15:10  岭南春  阅读(33)  评论(0)    收藏  举报