WPF向指定視窗傳送鍵盤指令
阿新 • • 發佈:2019-02-09
現在網上的庫大部分都是VB的那個傳送鍵盤指令的庫,那個在WPF裡面是用不了的,WPF的話可以用System.Windows.Forms中的其實跟VB中的Microsoft.VisualBasic.Devices這個裡面的SendKeys用法差不多一樣,吐槽一下,新的這個也可以在VB中使用好像,我看MSDN中Forms中的SendKeys也能在 VB中用,真是這一個小問題浪費了我一下午的時間。貼上程式碼
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow (string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpClass, string lpszWindow);
[DllImport("user32.dll ", EntryPoint = "SendMessage")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
[DllImport("user32.dll", EntryPoint = "SendMessage")]
public static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
const int WM_CHAR = 0x0102;
const int WM_SETTEXT = 0x000C;
const int VK_RETURN = 0x0d;
private void xin(object sender, RoutedEventArgs e)
{
Thread.Sleep(3000);
IntPtr handle = FindWindow(null, "vshost32.exe");
handle = FindWindowEx(handle, IntPtr.Zero, "Edit", null);
if (handle == IntPtr.Zero)
{
Console.WriteLine("沒有找到控制代碼");
// return;
}
SendMessage(handle, WM_SETTEXT, IntPtr.Zero, "d");
// SendKeys.Send("{TAB}");
//SendMessage(handle, WM_CHAR, (IntPtr)VK_RETURN, IntPtr.Zero);//Enter
SendKeys.SendWait("{d}");
// SendMessage(handle, WM_SETTEXT, IntPtr.Zero, "w");
}
這裡現在也還有很多我還不是很瞭解的地方,等以後有時間再說吧,現在要趕專案。
最後補充一下,它們其實就是很多個WIN32的API