C#獲取窗口,模擬按鍵操作


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("=");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM