zoukankan      html  css  js  c++  java
  • C# notepad自动打开文件 QQ登录 自动计算

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.Threading;
    using System.Windows.Forms;//这里面包含了SendKeys//要右键点击项目 添加System.Winodows.Forms引用
    using System.Runtime.InteropServices;
    using System.Management;//要右键点击项目 添加System.Management引用

    namespace MyAtuoTest1
    {
        class Program
        {
            private static uint LAUNCH_NOTEPAD_TIMEOUT = 300;
            private static void KillAllProcess(string processName)
            {
                Process[] procList = Process.GetProcessesByName(processName);
                foreach (Process proc in procList)
                {
                    proc.Kill();
                }
            }
            //检查Process是否忙碌
            private static bool WaitForProcessBusy(Process process, uint timeout)
            {
                uint waitTime = 0;
                do
                {
                    if (waitTime < timeout)
                    {
                        Thread.Sleep(2000);
                        waitTime += 2;
                    }
                    else
                    {
                        return false;
                    }
                } while (GetProcessCPUUsage(process) > 0);
                return true;
            }

            private static double GetProcessCPUUsage(Process process)
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT ProcessId FROM Win32_Process WHERE ProcessId = '" + process.Id + "'");
                if (searcher.Get().Count == 1)
                {
                    PerformanceCounter netmonCounter = new PerformanceCounter();
                    netmonCounter.CategoryName = "Process";
                    netmonCounter.CounterName = "% Processor Time";
                    netmonCounter.InstanceName = process.ProcessName;

                    PerformanceCounter cpuTotalCounter = new PerformanceCounter();
                    cpuTotalCounter.CategoryName = "Process";
                    cpuTotalCounter.CounterName = "% Processor Time";
                    cpuTotalCounter.InstanceName = "_Total";

                    cpuTotalCounter.NextValue();
                    netmonCounter.NextValue();
                    Thread.Sleep(20);
                    return Math.Round(100 * netmonCounter.NextValue() / cpuTotalCounter.NextValue(), 2);
                }
                else
                {
                    return -1;
                }
            }


             void testNotePad()
            {
                // launch notepad
                Process notepad = Process.Start(new ProcessStartInfo("notepad"));
                WaitForProcessBusy(notepad, LAUNCH_NOTEPAD_TIMEOUT);
                //Thread.Sleep(1000);

                IntPtr ptrNotepad = Win32.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Notepad", null);
                if (ptrNotepad == IntPtr.Zero)
                {
                    throw new Exception("launch notepad failed!");
                }
                Win32.ShowWindow(ptrNotepad, Win32.SW_SHOWMAXIMIZED);
                Thread.Sleep(1000);

                //press ctrl+O
                SendKeys.SendWait("^o");
                IntPtr penDialog = IntPtr.Zero;
                while (openDialog == IntPtr.Zero)
                {
                    Thread.Sleep(1000);
                    //32770 是对话框类型  “open” 是对话框标题 详细参数列表参见msdn
                    penDialog = Win32.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "#32770", "Open");
                }

                // find textBox
                // 通过Spy++ 可以看到edit的textBox在ComboBoxEx32下的comboBox中
                IntPtr tempPtr = Win32.FindWindowEx(openDialog, IntPtr.Zero, "ComboBoxEx32", null);
                tempPtr = Win32.FindWindowEx(tempPtr, IntPtr.Zero, "ComboBox", null);
                IntPtr edit = Win32.FindWindowEx(tempPtr, IntPtr.Zero, "Edit", null);//这里的edit句柄是一个textBox
                if (edit == IntPtr.Zero)
                {
                    throw new Exception("cannot find capture input editbox!");
                }

                //fill textBox
                // set the text of the edit control
                string filePath = @"D:Wircremianshi.txt";
                string penPath = "";
                for (int i = 0; i < filePath.Length; i++)
                {
                    IntPtr ptr = Marshal.StringToHGlobalAnsi(openPath + filePath[i]);
                    Win32.SendMessage(edit, Win32.WM_SETTEXT, 0, ptr);//向edit句柄发送消息
                    openPath += filePath[i];
                    Thread.Sleep(50);//每次在输入框中写上一个字就停顿50ms
                }
                SendKeys.SendWait("{End}");//模拟键盘上的End键
                Thread.Sleep(500);

                // Press 'Open' button
                IntPtr penButton = Win32.FindWindowEx(openDialog, IntPtr.Zero, "Button", "&Open");//&Open要加上&是因为O下面有下划线
                if (openButton == IntPtr.Zero)
                {
                    throw new Exception("cannot find capture open button!");
                }
                Win32.SendMessage(openButton, Win32.BM_CLICK, 0, 0);
                WaitForProcessBusy(notepad, LAUNCH_NOTEPAD_TIMEOUT);//似乎是等待 直到process不再忙碌

                SendKeys.SendWait("{ADD}");//OK!

            }

             void testQQ()
            {
                //launch qq
                Process qq = Process.Start(new ProcessStartInfo("D:\Program Files\Tencent\QQ\Bin\QQ.exe"));//注意转义符
                WaitForProcessBusy(qq, LAUNCH_NOTEPAD_TIMEOUT);
                IntPtr ptrQQ = Win32.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "TXGuiFoundation", "QQ2010");//第3个参数是ClassName
                if (ptrQQ == IntPtr.Zero)
                {
                    throw new Exception("launch QQ failed!");
                }
                Thread.Sleep(500);
                Console.WriteLine(" QQ launch OK!!");

                //account===========================
                IntPtr accountPtr = Win32.FindWindowEx(ptrQQ, IntPtr.Zero, "ATL:30A451E0", null);
                if (accountPtr == IntPtr.Zero)
                {
                    throw new Exception("cannot find capture input accountPtr!");
                }
                Console.WriteLine("account OK alt");

                string input = "12345679";
                string penPath = "";
                for (int i = 0; i < input.Length; i++)
                {
                    IntPtr ptr = Marshal.StringToHGlobalAnsi(openPath + input[i]);
                    Win32.SendMessage(accountPtr, Win32.WM_SETTEXT, 0, ptr);
                    openPath += input[i];
                    Thread.Sleep(50);
                }
                SendKeys.SendWait("{END}");
                Thread.Sleep(500);
                SendKeys.SendWait("{TAB}");
                Thread.Sleep(500);


                //Password============================
                SendKeys.SendWait("111");


                //press login
            }

            //事件
            private const int KEYEVENTF_KEYUP = 0x02;
            private const int KEYEVENTF_KEYDOWN = 0x00;

            void testCalc(){
                //launch calc
                Process calc = Process.Start(new ProcessStartInfo("calc"));
                WaitForProcessBusy(calc, LAUNCH_NOTEPAD_TIMEOUT);
                IntPtr ptrCalc = Win32.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "CalcFrame", "Calculator");//第3个参数是ClassName
                if (ptrCalc == IntPtr.Zero)
                {
                    throw new Exception("launch Calc failed!");
                }
                Thread.Sleep(500);
                Console.WriteLine(" calc launch OK!!");

                //prepare to calculate 32+45
                char[] nums = new char[] { '3', '2', '+', '4', '5', '=' };
                foreach (char i in nums)
                {
                    SendKeys.SendWait("{" + i + "}");
                    Thread.Sleep(100);
                }
                Console.WriteLine("keybd_event has passed");

            }

                
            static void Main(string[] args)
            {
                Program p = new Program();
                //p.testNotePad();
                //testQQ();
                p.testCalc();

            }
        }
    }



    ====================================================================
    //Win32.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace MyAtuoTest1
    {
        class Win32
        {
            public const int SW_SHOWMAXIMIZED = 3;
            public const int WM_SETTEXT = 0x000C;
            public const int BM_CLICK = 0x00F5;
            public const int LVM_FIRST = 0x1000;
            public const int LVM_GETITEMCOUNT = LVM_FIRST + 4;
            public const int LVM_GETITEM = LVM_FIRST + 75;//W
            public const int LVM_SETITEMSTATE = LVM_FIRST + 43;
            public const uint PROCESS_ALL_ACCESS = (uint)(0x000F0000L | 0x00100000L | 0xFFF);//0x1F0FFF;
            public const uint MEM_COMMIT = 0x1000;
            public const uint MEM_RELEASE = 0x8000;
            public const uint PAGE_READWRITE = 0x04;
            public const int LVIF_STATE = 0x0008;
            public const int LVIS_SELECTED = 0x0002;
            public const int LVIS_FOCUSED = 0x0001;
            public const int WM_VSCROLL = 0x0115;
            public const int SB_LINEDOWN = 1;

            [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
            public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childAfter, string className, string windowText);
            [DllImport("user32.dll", EntryPoint = "SendMessage")]
            public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, uint wParam, int lParam);

            [DllImport("user32.dll", EntryPoint = "ShowWindow")]
            public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

            [DllImport("user32.dll", EntryPoint = "SendMessage")]
            public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, uint wParam, IntPtr lParam);

            [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
            public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, ref uint lpProcessId);
            [DllImport("kernel32.dll", EntryPoint = "OpenProcess")]
            public static extern IntPtr OpenProcess(uint desiredAccess, bool inheritHandle, uint pid);


            [DllImport("kernel32.dll", EntryPoint = "VirtualAllocEx")]
            public static extern IntPtr VirtualAllocEx(IntPtr processHandle, IntPtr lpAddress, int dwSize, uint allocationType, uint protect);
            [DllImport("kernel32.dll", EntryPoint = "VirtualFreeEx")]
            public static extern bool VirtualFreeEx(IntPtr processHandle, IntPtr lpAddress, int dwSize, uint freeType);

            [DllImport("kernel32.dll", EntryPoint = "WriteProcessMemory")]
            public static extern bool WriteProcessMemory(IntPtr processHandle, IntPtr lpBaseAddress, IntPtr buf, int nSize, IntPtr lpNumberOfBytesWritten);
            [DllImport("kernel32.dll", EntryPoint = "ReadProcessMemory")]
            public static extern bool ReadProcessMemory(IntPtr processHandle, IntPtr lpBaseAddress, byte[] buf, int nSize, IntPtr lpNumberOfBytesRead);

            [DllImport("kernel32", EntryPoint = "CloseHandle")]
            public static extern bool CloseHandle(IntPtr hWnd);

            [DllImport("USER32.DLL")]
            public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);  //导入模拟键盘的方法
        }

        [StructLayout(LayoutKind.Sequential)]
        struct LV_ITEM
        {
            public uint mask;
            public uint iItem;
            public uint iSubItem;
            public uint state;
            public uint stateMask;
            public IntPtr pszText;
            public int cchTextMax;
            public int iImage;
            public int lParam;
            public int iIndent;
        }

    }

  • 相关阅读:
    tomcat遇到版本问题
    自定义文件上传的按钮的样式css+js
    js控制Bootstrap 模态框(Modal)插件
    jQuery-DataTables相关的网址
    在页面的el表达式是如何判断null的
    hibernate- Hibernate中多对多的annotation的写法(中间表可以有多个字段)
    apache.commons.compress 压缩,解压
    maven项目project facets中是2.3调整为3.0的解决办法
    eclipse中启动调试maven构建的javaweb项目
    [转]事务传播
  • 原文地址:https://www.cnblogs.com/wolly88/p/4278509.html
Copyright © 2011-2022 走看看