c# 獲取當前活動窗口句柄,獲取窗口大小及位置

需調用API函數html

需在開頭引入命名空間
using System.Runtime.InteropServices;數據庫

 

獲取當前窗口句柄:GetForegroundWindow()windows

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();api

 

返回值類型是IntPtr,即爲當前得到焦點窗口的句柄安全

使用方法 :   IntPtr myPtr=GetForegroundWindow();app

獲取到該窗口句柄後,能夠對該窗口進行操做.好比,關閉該窗口或在該窗口隱藏後,使其顯示函數

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);工具

 

其中ShowWindow(IntPtr hwnd, int nCmdShow);學習

nCmdShow的含義ui

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中的一些方法,找到目標窗口和進程以後把保存在數據庫中的用戶名密碼自動填入輸入框中,並登陸。

設計步驟:
1、調用Windows API。
 C#下調用Windows API方法以下:
 一、引入命名空間:using System.Runtime.InteropServices;
 二、引用須要使用的方法,格式:[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;

2、找到目標窗口
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);

3、向指定的窗口輸入數據
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

相關文章
相關標籤/搜索