通過Win32API調用另一界面的按鈕

功能說明

有兩個團隊創建的兩個相互獨立的winform界面,其中一個團隊在未知源碼的前提下,操作另一個團隊的界面的button。

展示

主界面如下:
主界面
子界面如下:
子界面
子界面有一按鈕(測試),點擊該按鈕,彈出“字窗體的提示內容”提示框。
當點擊父窗體(Form1)上的按鈕(button1)時,可以操作子窗體(子窗體的窗體)的按鈕(測試),並出現提示框

代碼

子窗體的代碼:

namespace TestForm
{
    public partial class MyTestForm : Form
    {
        public MyTestForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("子窗體的提示內容!");
        }
    }
}

父窗體的代碼

    public partial class Form1 : Form
    {
        [DllImport("user32.dll", EntryPoint = "FindWindowA", 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);  

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //Process.Start("TestForm.exe");

                const int WM_CLICK = 0x00F5;//鼠標點擊消息,各種消息的數值,可以參考MSDN  

                string lpszName_TestChild = "子窗體的窗體";//子窗體的標題(Text屬性值)  
                string lpszName_btnYes = "測試";//子窗體上button的標題(Text屬性值)  

                IntPtr hwndTestChild = new IntPtr();//子窗體的句柄  
                IntPtr hwndbtnYes = new IntPtr();//子窗體上button的句柄  

                hwndTestChild = FindWindow(null, lpszName_TestChild);//獲取子窗體的句柄  
                hwndbtnYes = FindWindowEx(hwndTestChild, 0, null, lpszName_btnYes);//獲取子窗體上button的句柄  

                if (hwndTestChild != IntPtr.Zero)
                {
                    SendMessage(hwndbtnYes, WM_CLICK, 0, 0);//給子窗體上button發送鼠標點擊消息,  
                }
                else
                {
                    MessageBox.Show("未找到!");
                }


            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }


    }

其他說明

1、方法說明中:

    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
   private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

此處EntryPoint = “FindWindow”或EntryPoint = “FindWindowA”均可。
本人環境VS2010,Win7旗艦。之前FindWindow的返回結果一直是0。但不知爲何又好了。

2、關於session0的相關問題:

1、關於部分WIN32 API 在WIN 7下失效的問題
2、Session 0 Isolation
3、FindWindow始終返回0

3、參考資料

進程間的通信

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