程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C# 獲得窗口控件句柄

C# 獲得窗口控件句柄

編輯:C#基礎知識
[DllImport("User32.dll", EntryPoint = "FindWindow")]
    private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

    [DllImport("user32.dll", EntryPoint = "FindWindowEx",SetLastError = true)]
    private static extern IntPtr FindWindowEx(IntPtr hwndParent,IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

    [DllImport("User32.dll", EntryPoint = "SendMessage")]
    private static extern int SendMessage(IntPtr hWnd,int Msg, IntPtr wParam, string lParam);

    const int WM_GETTEXT = 0x000D;
    const int WM_SETTEXT = 0x000C;
    const int WM_CLICK = 0x00F5;

    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        int retval = 0; //增加一個返回值用來判斷操作是否成功
        //string lpszParentClass = "#32770"; //整個窗口的類名
        string lpszParentWindow = "Form1"; //窗口標題
        string lpszClass = "WindowsForms10.EDIT.app.0.b7ab7b"; //需要查找的子窗口的類名,也就是輸入框
        //string lpszClass = "Edit";
        string lpszClass_Submit = "WindowsForms10.BUTTON.app.0.b7ab7b"; //需要查找的Button的類名
        //string lpszClass_Submit = "Button";
        string lpszName_Submit = "確定"; //需要查找的Button的標題
        string text = "";

        IntPtr ParenthWnd = new IntPtr(0);
        IntPtr EdithWnd = new IntPtr(0);

        //查到窗體,得到整個窗體
        ParenthWnd = FindWindow(null, lpszParentWindow);

        //判斷這個窗體是否有效
        if (!ParenthWnd.Equals(IntPtr.Zero))
        {
          //得到Form1這個子窗體的文本框,並設置其內容
          EdithWnd = FindWindowEx(ParenthWnd, EdithWnd, lpszClass, "");   [color=#FF0000]這裡獲取到的EdithWnd始終為0;[/color]
        
          if (!EdithWnd.Equals(IntPtr.Zero))
          {
            text = "test1";
            //調用SendMessage方法設置其內容
            SendMessage(EdithWnd, WM_SETTEXT, IntPtr.Zero, text);
            retval++;
          }
        
          //得到Button這個子窗體,並觸發它的Click事件
          EdithWnd = FindWindowEx(ParenthWnd,
          (IntPtr)0, lpszClass_Submit, lpszName_Submit);
          if (!EdithWnd.Equals(IntPtr.Zero))
          {
            SendMessage(EdithWnd, WM_CLICK, (IntPtr)0, "0");
            retval++;
          }
        }
    }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved