C#獲取窗口,模擬按鍵操作,實現計算器模擬操作。

首先引用。
using System.Runtime.InteropServices;
使用DllImport引入兩個函數:
// Get a handle to an application window. [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); // Activate an application window. [DllImport("USER32.DLL")] public static extern bool SetForegroundWindow(IntPtr hWnd);
然后首先使用FindWindow函數獲取到需要按鍵的窗口句柄,以計算器為例。
//FindWindow 參數一是進程名 參數2是 標題名 IntPtr calculatorHandle = FindWindow(null, "計算器"); //判斷是否找到 if (calculatorHandle == IntPtr.Zero) { MessageBox.Show("沒有找到!"); return; } // 然后使用SetForegroundWindow函數將這個窗口調到最前。 SetForegroundWindow(calculatorHandle); //發送按鍵 SendKeys.SendWait("2"); SendKeys.SendWait("*"); SendKeys.SendWait("11"); SendKeys.SendWait("=");
