控制別人的程序的按鈕和編輯控件等

[DllImport("user32.dll")]
 static extern IntPtr FindWindow(string strClass, string strWindow);
 [DllImport("user32.dll")]
 static extern IntPtr FindWindowEx(HandleRef hwndParent, HandleRef hwndChildAfter, string strClass, string    strWindow); 

 [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true,CharSet=CharSet.Auto)]
 private static extern int SendMessage 1(IntPtr hwnd, uint wMsg, int wParam, string lParam); 

                                                                                                                      //調用windows提供的API函數 

 Intptr ptrTaskbar = FindWindow("#32770", "Form1"); 

 Intptr ptrNextBtn = FindWindowEx(new HandleRef(this, ptrTaskbar), new HandleRef(this, IntPtr.Zero), "ComboBox","");                                                //找到combobox的句柄 

 SetForegroundWindow(ptrTaskbar);                      //將combobox的父窗口設爲當前活動窗口
 SendMessage(ptrNextBtn, CB_SHOWDROPDOWN, 1, 0);//打開列表  

 string ptr = "研究生";                                               //combobox裏之前有初中生、高中生、大學生、研究生
 SendMessage1(ptrNextBtn, CB_SELECTSTRING, 0, ptr );//選擇 
 SendMessage(ptrNextBtn, WM_KEYDOWN, VK_RETURN, 0);  //響應回車鍵 
 SendMessage(ptrNextBtn, CB_SHOWDROPDOWN,0, 0); //關閉列表   

 System.Threading.Thread.Sleep(50);                        //延時50ms,如果機器速度慢,可以增加延時時間    

經測試程序好用。如果有問題,應該是在findwindow函數的標題或者combobox的句柄有問題。 

ptrNextBtn = FindWindowEx(new HandleRef(this, ptrTaskbar), new HandleRef(this, IntPtr.Zero), "ComboBox","");中的ptrTaskbar必須是combobox的上一個父窗口的句柄,如果時期上上級父窗口肯定會出錯的。

以上代碼可以參考,另外幾篇文章可以參考。

http://www.yourdelphi.com/topic_511449_49e0.htm

http://www.yourdelphi.com/topic_76208_02d7.htm

http://www.yourdelphi.com/topic_511597_5918.htm

http://blog.csdn.net/nvidiacuda/article/details/4371535

幾個關鍵的函數是

1、FindWindow(NULL,"你要找的窗口標題"); //得到目標窗體的handle
2、findwindowEx(...)edit的HWND;//得到目標edit的handle 
3、SendMessage(hWnd,WM_SETTEXT,0,(LPARAM)temp);//hWnd爲edit的handle ,temp是要發送的文本


關於獲取句柄可以使用SPY軟件,可以百度查SPY軟件的用法。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章