Rocho.J

人脑是不可靠的, 随时记录感悟并且经常重复!

 

[转]C#获得控件的句柄 ---------- 转自:http://blog.sina.com.cn/s/blog_53864cba01016zkx.html

[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, stringlpszClass, 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++;
          }
        }
    }

posted on 2014-12-02 18:33  RJ  阅读(176)  评论(0编辑  收藏  举报

导航