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:\Wircre\mianshi.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;
    }

}

时间: 2024-10-12 16:13:21

C# notepad自动打开文件 QQ登录 自动计算的相关文章

如何通过第三方QQ登录网站首页

QQ登录,就是我们所说的第三方登录,是指用户可以不在本项目中输入密码,而直接通过第三方的验证,成功登录本项目 若想实现QQ登录,需要成为QQ互联的开发者,审核通过才可实现.注册方法参考链接http://wiki.connect.qq.com/%E6%88%90%E4%B8%BA%E5%BC%80%E5%8F%91%E8%80%85 成为QQ互联开发者后,还需创建应用,即获取本项目对应与QQ互联的应用ID,最重要的是拿到APPID,创建应用的方法参考链接http://wiki.connect.qq

批处理自动打开Hosts文件

之前写了一个备份还原Hosts文件的批处理,之后有人反映每次打开Hosts文件的路径太复杂,桌面生成快捷方式容易被清理掉,所以又写了个批处理自动打开Hosts文件,保存为.bat格式或者编译成exe格式运行即可,代码如下: @echo off start  notepad.exe C:\Windows\System32\drivers\etc\hosts exit

win10 32位自动应答文件自动登录红色背景解决方案。

我在制作win10 自动应答文件时候在32位系统上发现一个问题,在登录过程中会出现红色背景的现象,但是通过重启是可以解决这个问题的,如果在大量部署install.wim是这似乎是非常麻烦的.这里提供一个解决方案,希望可以帮助大家. 1.在我创建的通用应答文件中增加两个参数如图 : 这样当系统部署完毕后会自动注销一次,等待用户登录.用户登录后红色背景的图片就消失了,以后这个系统就不会再出现红色背景的现象了.这个批处理和自动应答文件命令不仅可以解决红色背景问题还可以加快系统安装速度. 我把我写的批处

WebBrowser自动填充打开文件对话框

WebBrowser自动填充打开文件对话框 在使用WebBrowser编写自动表单填写软件的时候,不知道大家是否遇到国填写文件选择表单的情况.遇到这种情况的时候,无法直接队Html元素赋值,必须模拟手工选择的办法(是否有其它解决办法,不得而知),下面我们来说一下我的解决办法,如下: 1.先说一下正常表单的填写方式,在Delphi+WebBrowser的环境下,可采用如下代码: 1 WebBrowser.OleObject.document.all.item('XXX', 0).value :=x

sublime打开文件时自动生成并打开.dump文件

GBK Encoding Support 没有安装前打开ASNI格式编码文件会乱码,安装成功重启则可以打开正常 关于.dump文件生成的解释: 当打开一个非utf-8格式且包含汉字的文件时,sublime text 2会自动生成一个dump文件,文件修改过程中,不会修改原文件,只有按"保存"了才会将dump的数据更新到原文件里,关闭当前编辑的dump文件则会自动删除dump文件. 但是有时候 GBK Encoding Support 插件也会出些bug,就想这样,生成.dump文件后自

Centos自动登录系统并自动打开VNC Server

系统自动登录 修改配置文件 sudo vim /etc/gdm/custom.conf 增加配置 [daemon] AutomaticLogin=spark AutomaticLoginEnable=True 开机自动打开VNC Server 开启VNC Server Service自动启动 sudo setup 按Tab键选择“System Services" 找到”vncserver",按空格键选中 按Tab键选择“OK”并按空格键确认保存 修改配置文件 sudo vim /etc

VS15 preview 5打开文件夹自动生成slnx.VC.db SQLite库疑惑?求解答

用VS15 preview 5打开文件夹(详情查看博客http://www.cnblogs.com/zsy/p/5962242.html中配置),文件夹下多一个slnx.VC.db文件,如下图: 本文件是SQLite文件,通过Navicat Premium打开,配置如下: 打开如下: 一共有14张数据表.其中以下3张表有数据: 各个表与字段含义,从官网也没有找到相关解释,还有待考证:其中个别表可以从命名来理解,例如properties,表示属性.有知情者请告诉一二,如向本人获取Navicat P

QQ登录网站接入功能实现--非官方文档搬运

背景 最近第一次使用QQ登录功能,期间遇到这种问题,在网上找了很多资料,大多都是官方的搬运,并没有真正的干料,可能是个人能力问题,遇到了各种麻烦,折腾了几天,最终弄好,在这里记录一下和大家分享,希望对大家有所帮助. 由于官方文档已经对如何使用API接口做出了很明确的说明,所以这里我只是记录我在开发过程中一些步骤中遇到的问题和注意的事项,详细步骤请参考官方文档:http://wiki.connect.qq.com/ 开发环境:SpringMVC.QQ登录Java SDK版.Maven.IDEA 应

如何本地测试例如QQ登录等第三方接口

前言:现在基本是个网站就会集成第三方的一些接口,比如QQ登录.分享等等.但是在开发的时候,尤其是没有这方面经验的开发人员来说,调试流程时会显得迷茫,不知道怎么调试.这里就个人的这方面学习摸索做一个总结. 如题,本篇只是总结 如何本地测试例如QQ登录等第三方接口. 特别说明:1.本文以集成QQ登录接口为例.2.因为是NET程序猿,所以以VS举例说明 关于如何成为QQ开发者,如何申请AppID以及AppKey,不再赘述!百度百科上都有了,还说什么呢!呵呵~ 关于如何集成,这个官网上都有各种SDK,而