2014-01-15 154 views
-3

我想做一个非常简单的程序,我需要模拟一个按键。我试图找到一个解决方案,但我的程序似乎并不知道任何建议的方法。我不知道这是因为我正在使用控制台应用程序还是交易是什么,但是没有简单的发送虚拟按键的方法,计算机会作出反应,就好像用户自己碰到按钮?模拟按键

+1

[Google上首次访问](http://social.msdn.microsoft.com/Forums/windows/en-US/f1b195b7-1568-46f5-83bb-e1e85b188af2/how-to-simulate-a-key- press-in-c?forum = winforms) –

+0

你的问题质量很差。有些关于*的更多信息正是你想要完成的。 –

+0

“Simulating Key Press c#”对我来说是一个低潮期。在Thejaka Maldeniya的回答中,我发现我需要使用System.Windows.Forms。但是现在我得到了我回应的错误。 我只需要模拟一个按键。假设我想模拟空间按钮。如果我在Word中,它会占用一个空间,如果我在VLC中,它会暂停视频,如果我在游戏中,我可能会跳。 – user3026046

回答

1

目前还不清楚您是否想要模拟您自己的应用程序或正在计算机上运行的第三方应用程序/窗口的按键。我会假设后者。

下面的最小示例将发送Hello world!记事本的一个实例,您必须手动启动该实例。

static void Main(string[] args) 
{ 
    // Get the 'notepad' process. 
    var notepad = Process.GetProcessesByName("notepad").FirstOrDefault(); 
    if (notepad == null) 
     throw new Exception("Notepad is not running."); 

    // Find its window. 
    IntPtr window = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero, 
     "Edit", null); 

    // Send some string. 
    SendMessage(window, WM_SETTEXT, 0, "Hello world!"); 
} 

full code

它用这些PInvoke的方法和常量:

[DllImport("user32.dll")] 
public static extern IntPtr FindWindowEx(IntPtr hwndParent, 
    IntPtr hwndChildAfter, string lpszClass, string lpszWindow); 

[DllImport("User32.dll")] 
public static extern int SendMessage(IntPtr hWnd, int uMsg, 
    int wParam, string lParam); 

private const int WM_SETTEXT = 0x000C; 

谷歌是你的朋友,当你想了解更多关于如何获得你想要的应用程序句柄,PInvoke,并发送消息到其他应用程序。