需調用API函數
需在開頭引入命名空間
using System.Runtime.InteropServices;
獲取當前窗口句柄:GetForegroundWindow()
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
返回值類型是IntPtr,即為當前獲得焦點窗口的句柄
使用方法 : IntPtr myPtr=GetForegroundWindow();
獲取到該窗口句柄后,可以對該窗口進行操作.比如,關閉該窗口或在該窗口隱藏后,使其顯示
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
其中ShowWindow(IntPtr hwnd, int nCmdShow);
nCmdShow的含義
0 關閉窗口
1 正常大小顯示窗口
2 最小化窗口
3 最大化窗口
使用實例: ShowWindow(myPtr, 0);
獲取窗口大小及位置:需要調用方法GetWindowRect(IntPtr hWnd, ref RECT lpRect)
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; //最左坐標
public int Top; //最上坐標
public int Right; //最右坐標
public int Bottom; //最下坐標
}
示例:
InPtr awin = GetForegroundWindow(); //獲取當前窗口句柄
RECT rect = new RECT();
GetWindowRect(awin, ref rect);
int width = rc.Right - rc.Left; //窗口的寬度
int height = rc.Bottom - rc.Top; //窗口的高度
int x = rc.Left;
int y = rc.Top;
------------------------------------------------------------------------
C#中的FindWindow
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint="FindWindow")]
public static extern int FindWindow (
string lpClassName,
string lpWindowName
);
已知窗口標題"abc",怎么得到窗口句柄?
IntPtr hWnd = FindWindow(null, "abc");
-------------------------------------------------------
C#使用FindWindow()函數:
[DllImport("coredll.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
這個函數有兩個參數,第一個是要找的窗口的類,第二個是要找的窗口的標題。在搜索的時候不一定兩者都知道,但至少要知道其中的一個。有的窗口的標題是比較容易得到的,如"計算器",所以搜索時應使用標題進行搜索。但有的軟件的標題不是固定的,如"記事本",如果打開的文件不同,窗口標題也不同,這時使用窗口類搜索就比較方便。如果找到了滿足條件的窗口,這個函數返回該窗口的句柄,否則返回0。 看例子
IntPtr ParenthWnd = new IntPtr(0);
ParenthWnd = FindWindow(null,"Word Mobile");
//判斷這個窗體是否有效
if (ParenthWnd != IntPtr.Zero)
{
MessageBox.Show("找到窗口");
}
else
MessageBox.Show("沒有找到窗口");
從上面的討論中可以看出,如果要搜索的外部程序的窗口標題比較容易得到,問題是比較簡單的。可如果窗口的標題不固定或者根本就沒有標題,怎么得到窗口的類呢?如果你安裝了Visual C++,你可以使用其中的Spy,在Spy++中有一個FindWindow工具,它允許你使用鼠標選擇窗口,然后Spy++會顯示這個窗口的類。
在Win32 API中還有一個FindWindowEx,它非常適合尋找子窗口。
FindWindowEx用法
函數功能:該函數獲得一個窗口的句柄,該窗口的類名和窗口名與給定的字符串相匹配。這個函數查找子窗口,從排在給定的子窗口后面的下一個子窗口開始。在查找時不區分大小寫。
函數原型:HWND FindWindowEx(HWND hwndParent,HWND hwndChildAfter,LPCTSTR lpszClass,LPCTSTR lpszWindow);
參數:
hwndParent:要查找子窗口的父窗口句柄。
如果hwnjParent為NULL,則函數以桌面窗口為父窗口,查找桌面窗口的所有子窗口。
Windows NT5.0 and later:如果hwndParent是HWND_MESSAGE,函數僅查找所有消息窗口。
hwndChildAfter :子窗口句柄。查找從在Z序中的下一個子窗口開始。子窗口必須為hwndPareRt窗口的直接子窗口而非后代窗口。如果HwndChildAfter為NULL,查找從hwndParent的第一個子窗口開始。如果hwndParent 和 hwndChildAfter同時為NULL,則函數查找所有的頂層窗口及消息窗口。
lpszClass:指向一個指定了類名的空結束字符串,或一個標識類名字符串的成員的指針。如果該參數為一個成員,則它必須為前次調用theGlobaIAddAtom函數產生的全局成員。該成員為16位,必須位於lpClassName的低16位,高位必須為0。
lpszWindow:指向一個指定了窗口名(窗口標題)的空結束字符串。如果該參數為 NULL,則為所有窗口全匹配。返回值:如果函數成功,返回值為具有指定類名和窗口名的窗口句柄。如果函數失敗,返回值為NULL。
C#中使用該函數首先導入命名空間:
01.using System.Runtime.InteropServices;
然后寫API引用部分的代碼,放入 class 內部
01.[DllImport("user32.dll", EntryPoint = "FindWindow")]
02.private static extern IntPtr FindWindowEx( IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow )
例如:
01.const int BM_CLICK = 0xF5;
02.IntPtr maindHwnd = FindWindow(null, "QQ用戶登錄"); //獲得QQ登陸框的句柄
03.if (maindHwnd != IntPtr.Zero)
04.{
05. IntPtr childHwnd = FindWindowEx(maindHwnd, IntPtr.Zero, null, "登錄"); //獲得按鈕的句柄
06. if (childHwnd != IntPtr.Zero)
07. {
08. SendMessage(childHwnd, BM_CLICK, 0, 0); //發送點擊按鈕的消息
09. }
10. else
11. {
12. MessageBox.Show("沒有找到子窗口");
13. }
14.}
15.else
16.{
17. MessageBox.Show("沒有找到窗口");
18.}
從此學習網 http://item.congci.com/item/findwindowfindwindowex
---------------------------------------------------------------------------------------
DllImport("user32", SetLastError = true)]
public static extern int GetWindowText(
IntPtr hWnd,//窗口句柄
StringBuilder lpString,//標題
int nMaxCount //最大值
);
//獲取類的名字
[DllImport("user32.dll")]
private static extern int GetClassName(
IntPtr hWnd,//句柄
StringBuilder lpString, //類名
int nMaxCount //最大值
);
//根據坐標獲取窗口句柄
[DllImport("user32")]
private static extern IntPtr WindowFromPoint(
Point Point //坐標
);
private void timer1_Tick(object sender, EventArgs e)
{
int x = Cursor.Position.X;
int y = Cursor.Position.Y;
Point p = new Point(x, y);
IntPtr formHandle = WindowFromPoint(p);//得到窗口句柄
StringBuilder title = new StringBuilder(256);
GetWindowText(formHandle, title, title.Capacity);//得到窗口的標題
StringBuilder className = new StringBuilder(256);
GetClassName(formHandle, className, className.Capacity);//得到窗口的句柄
this.textBox1.Text = title.ToString();
this.textBox2.Text = formHandle.ToString();
this.textBox3.Text = className.ToString();
}
--------------------------------------
文章不錯,收藏備用。
設計初衷:
公司為了安全性考慮,不讓密碼被太多人知道,所以想實現一個自動登錄的模塊。
設計思想:
主要是通過調用Windows API中的一些方法,找到目標窗口和進程之后把保存在數據庫中的用戶名密碼自動填入輸入框中,並登錄。
設計步驟:
一、調用Windows API。
C#下調用Windows API方法如下:
1、引入命名空間:using System.Runtime.InteropServices;
2、引用需要使用的方法,格式:[DllImport("DLL文件")]方法的聲明;
[DllImport("user32.dll")]private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);
[DllImport("user32.dll")]private static extern int SendMessage(IntPtr hWnd,int Msg,int wParam,int lParam);
[DllImport("user32.dll")]private static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
[DllImport("user32.dll")]private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
[DllImport("user32.dll")]private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags);
//ShowWindow參數
private const int SW_SHOWNORMAL = 1;
private const int SW_RESTORE = 9;
private const int SW_SHOWNOACTIVATE = 4;
//SendMessage參數
private const int WM_KEYDOWN = 0X100;
private const int WM_KEYUP = 0X101;
private const int WM_SYSCHAR = 0X106;
private const int WM_SYSKEYUP = 0X105;
private const int WM_SYSKEYDOWN = 0X104;
private const int WM_CHAR = 0X102;
二、找到目標窗口
1)、根據窗口的標題得到句柄
IntPtr myIntPtr = FindWindow(null,"窗口名"); //null為類名,可以用Spy++得到,也可以為空
ShowWindow(myIntPtr, SW_RESTORE); //將窗口還原
SetForegroundWindow(myIntPtr); //如果沒有ShowWindow,此方法不能設置最小化的窗口
2)、遍歷所有窗口得到句柄
1 定義委托方法CallBack,枚舉窗口API(EnumWindows),得到窗口名API(GetWindowTextW)和得到窗口類名API(GetClassNameW)
public delegate bool CallBack(int hwnd, int lParam);
[DllImport("user32")]public static extern int EnumWindows(CallBack x, int y);
[DllImport("user32.dll")]private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);
2 調用EnumWindows遍歷窗口
CallBack myCallBack = new CallBack(Recall);
EnumWindows(myCallBack, 0);
3 回調方法Recall
public bool Recall(int hwnd, int lParam)
{
StringBuilder sb = new StringBuilder(256);
IntPtr PW = new IntPtr(hwnd);
GetWindowTextW(PW,sb,sb.Capacity); //得到窗口名並保存在strName中
string strName = sb.ToString();
GetClassNameW(PW,sb,sb.Capacity); //得到窗口類名並保存在strClass中
string strClass = sb.ToString();
if (strName.IndexOf("窗口名關鍵字") >= 0 && strClass.IndexOf("類名關鍵字") >= 0)
{
return false; //返回false中止EnumWindows遍歷
}
else
{
return true; //返回true繼續EnumWindows遍歷
}
}
3)、打開窗口得到句柄
1 定義設置活動窗口API(SetActiveWindow),設置前台窗口API(SetForegroundWindow)
[DllImport("user32.dll")]static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)]static extern bool SetForegroundWindow(IntPtr hWnd);
2 打開窗口
Process proc = Process.Start(@"目標程序路徑");
SetActiveWindow(proc.MainWindowHandle);
SetForegroundWindow(proc.MainWindowHandle);
三、向指定的窗口輸入數據
1 利用發送消息API(SendMessage)向窗口發送數據
InputStr(myIntPtr, _GameID); //輸入游戲ID
SendMessage(myIntPtr, WM_SYSKEYDOWN, 0X09, 0); //輸入TAB(0x09)
SendMessage(myIntPtr, WM_SYSKEYUP, 0X09, 0);
InputStr(myIntPtr, _GamePass); //輸入游戲密碼
SendMessage(myIntPtr, WM_SYSKEYDOWN, 0X0D, 0); //輸入ENTER(0x0d)
SendMessage(myIntPtr, WM_SYSKEYUP, 0X0D, 0);
/// <summary>
/// 發送一個字符串
/// </summary>
/// <param name="myIntPtr">窗口句柄</param>
/// <param name="Input">字符串</param>
public void InputStr(IntPtr myIntPtr, string Input)
{
byte[] ch = (ASCIIEncoding.ASCII.GetBytes(Input));
for (int i = 0; i < ch.Length; i++)
{
SendMessage(PW, WM_CHAR, ch, 0);
}
}
2 利用鼠標和鍵盤模擬向窗口發送數據
SetWindowPos(PW, (IntPtr)(-1), 0, 0, 0, 0, 0x0040 | 0x0001); //設置窗口位置
SetCursorPos(476, 177); //設置鼠標位置
mouse_event(0x0002, 0, 0, 0, 0); //模擬鼠標按下操作
mouse_event(0x0004, 0, 0, 0, 0); //模擬鼠標放開操作
SendKeys.Send(_GameID); //模擬鍵盤輸入游戲ID
SendKeys.Send("{TAB}"); //模擬鍵盤輸入TAB
SendKeys.Send(_GamePass); //模擬鍵盤輸入游戲密碼
SendKeys.Send("{ENTER}"); //模擬鍵盤輸入ENTER
另:上面還提到了keybd_event方法,用法和mouse_event方法類似,作用和SendKeys.Send一樣。
C# 別人軟件里邊做好的文本框,我如何給他賦值並且提交,最好有源碼可供參考,如有合適的,將高額追加分
可以用WINDOWS api函數實現。
下面的WINDIWS API引用部分的代碼,放入 class 內部
[DllImport ( "user32.dll", EntryPoint = "FindWindow", SetLastError = true )]
private static extern IntPtr FindWindow( string lpClassName, string lpWindowName );//查找窗口句柄
[DllImport ( "user32.dll", EntryPoint = "FindWindowEx", SetLastError = true )]
private static extern IntPtr FindWindowEx( IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow );//查找窗口內控件句柄
[DllImport ( "user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto )]
private static extern int SendMessage( IntPtr hwnd, uint wMsg, int wParam, int lParam );//發送消息
[DllImport ( "user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true )]
private static extern void SetForegroundWindow( IntPtr hwnd );// 設置窗口為激活狀態
哈哈,現在可以開工了。我就用QQ的自動登錄為列子
下面是你winfrom窗口的按鈕事件:
private void button1_Click( object sender, EventArgs e )
{
const uint WM_SETTEXT = 0x000C;//設置文本框內容的消息
const uint BM_CLICK = 0xF5; //鼠標點擊的消息,對於各種消息的數值,你還是得去查查API手冊
IntPtr hwndCalc = FindWindow ( null, "QQ2011" ); //查找QQ2011的窗口句柄
if ( hwndCalc != IntPtr.Zero )//找到啦
{
IntPtr hwndLogin= FindWindowEx ( hwndCalc, 0, null, "安全登錄" ); //獲取登陸按鈕的句柄
IntPtr hwndQ = FindWindowEx ( hwndCalc, 0, “ComboBox”, "" ); //獲取QQ號碼輸入框的控件句柄
IntPtr hwndP = FindWindowEx ( hwndCalc, 0,"Edit", “” ); //獲取密碼輸入框的控件句柄 SetForegroundWindow ( hwndCalc ); //將QQ窗口設置為激活
System.Threading.Thread.Sleep ( 1000 ); //暫停1秒讓你看到效果
SendMessage ( hwndQ, WM_SETTEXT, TextBox1.Text, 0 );//發送文本框1里面的內容(QQ號啦)
System.Threading.Thread.Sleep ( 1000 ); //暫停1秒讓你看到效果
SendMessage( hwndP, WM_SETTEXT, TextBox2.Text, 0 );//發送文本框2里面的內容(QQpassword)
System.Threading.Thread.Sleep ( 1000); //暫停1秒讓你看到效果
SendMessage ( hwndLogin, BM_CLICK, 0, 0 );//點擊登錄
}
else
{
MessageBox.Show ("沒有啟動 [QQ2011]");
}
}
---------------------------------------------------
C#查找指定窗口的子窗口的句柄
2009年更新
通過實驗得知,FindWindowEx可以通過classname或caption(也就是窗口的title)查找窗口,且如果第一個參數傳IntPtr.Zero的話,將從Windows最頂層窗口開始查找,但是窗口很多的話這樣會非常的慢,所以加入Timeout的判斷,如果超時還沒找到,返回false。
用法:FindWindow fw = new FindWindow(IntPtr.Zero, null, "ThunderDFrame", 10);//查找Title為ThunderDFrame的窗口,如果10秒內還沒找到,返回false
代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Util { class FindWindow { [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] //IMPORTANT : LPARAM must be a pointer (InterPtr) in VS2005, otherwise an exception will be thrown private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i); //the callback function for the EnumChildWindows private delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter); //if found return the handle , otherwise return IntPtr.Zero [DllImport("user32.dll", EntryPoint = "FindWindowEx")] private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); private string m_classname; // class name to look for private string m_caption; // caption name to look for private DateTime start; private int m_timeout;//If exceed the time. Indicate no windows found. private IntPtr m_hWnd; // HWND if found public IntPtr FoundHandle { get { return m_hWnd; } } private bool m_IsTimeOut; public bool IsTimeOut { get{return m_IsTimeOut;} set { m_IsTimeOut = value; } } // ctor does the work--just instantiate and go public FindWindow(IntPtr hwndParent, string classname, string caption, int timeout) { m_hWnd = IntPtr.Zero; m_classname = classname; m_caption = caption; m_timeout = timeout; start = DateTime.Now; FindChildClassHwnd(hwndParent, IntPtr.Zero); } /**/ /// <summary> /// Find the child window, if found m_classname will be assigned /// </summary> /// <param name="hwndParent">parent's handle</param> /// <param name="lParam">the application value, nonuse</param> /// <returns>found or not found</returns> //The C++ code is that lParam is the instance of FindWindow class , if found assign the instance's m_hWnd private bool FindChildClassHwnd(IntPtr hwndParent, IntPtr lParam) { EnumWindowProc childProc = new EnumWindowProc(FindChildClassHwnd); IntPtr hwnd = FindWindowEx(hwndParent, IntPtr.Zero, m_classname, m_caption); if (hwnd != IntPtr.Zero) { this.m_hWnd = hwnd; // found: save it m_IsTimeOut = false; return false; // stop enumerating } DateTime end = DateTime.Now; if (start.AddSeconds(m_timeout) < end) { m_IsTimeOut = true; return false; } EnumChildWindows(hwndParent, childProc, IntPtr.Zero); // recurse redo FindChildClassHwnd return true;// keep looking }
出處:https://blog.csdn.net/pangwenquan5/article/details/40317773