網頁

2011年6月19日 星期日

C#用 SendKyes 結合 FindWindow 虛擬鍵盤控制外部程式


C# 利用 Windows API 控制 外部的 win32 程序

我們這裡,用控制 「計算器」程序,算一個 3 + 2 = 5 的算式來做示例。
API 中我們要用到的函數有 FindWindowFindWindowExSendMessageSetForegroundWindow
要使用API,需要引入命名空間

using System.Runtime.InteropServices;

下面的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 );



private void button1_Click( object sender, EventArgs e )
{
    const uint BM_CLICK = 0xF5; //鼠標點擊的消息,對於各種消息的數值,大家還是得去API手冊

    IntPtr hwndCalc = FindWindow ( null, "小算盤" ); //查找小算盤標題

    if ( hwndCalc != IntPtr.Zero )
    {
    IntPtr hwndThree = FindWindowEx ( hwndCalc, 0, null, "3" ); //獲取按鈕3 的句柄

    IntPtr hwndPlus = FindWindowEx ( hwndCalc, 0, null, "+" );  //獲取按鈕 + 的句柄
    IntPtr hwndTwo = FindWindowEx ( hwndCalc, 0, null, "2" );  //獲取按鈕2 的句柄
    IntPtr hwndEqual = FindWindowEx ( hwndCalc, 0, null, "=" ); //獲取按鈕= 的句柄
    SetForegroundWindow ( hwndCalc );    //將計算器設為當前活動窗口
    System.Threading.Thread.Sleep ( 2000 );   //暫停2秒讓你看到效果
    SendMessage ( hwndThree, BM_CLICK, 0, 0 );
    System.Threading.Thread.Sleep ( 2000 );   //暫停2秒讓你看到效果
    SendMessage ( hwndPlus, BM_CLICK, 0, 0 );
    System.Threading.Thread.Sleep ( 2000 );   //暫停2秒讓你看到效果
    SendMessage ( hwndTwo, BM_CLICK, 0, 0 );
    System.Threading.Thread.Sleep ( 2000 );   //暫停2秒讓你看到效果
    SendMessage ( hwndEqual, BM_CLICK, 0, 0 );

    System.Threading.Thread.Sleep ( 2000 );
    MessageBox.Show ("你看到結果了嗎?");
    }
    else
    {
    MessageBox.Show ("沒有啟動 [小算盤]");
    }
}

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。