模拟键盘在C#中输入键

时间:2016-04-21 21:37:21

标签: c# .net remote-desktop rdp

我正在尝试模拟Win7中的各种任务,我对此功能有一些问题:

LeftMouseClick(Cursor.Position.X - 720, Cursor.Position.Y - 45);
System.Threading.Thread.Sleep(1000);

// Simulate each key stroke
InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);
InputSimulator.SimulateKeyUp(VirtualKeyCode.RETURN);

InputSimulator.SimulateTextEntry("cmd");
System.Threading.Thread.Sleep(1000);


InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);
InputSimulator.SimulateKeyUp(VirtualKeyCode.RETURN);

我想做的就是按START,写cmd,按回车键。除了按下回车键之外,所有工作都很顺利。

所有这些都发生在RDP ActiveX上,这里是代码:

var client = (IMsRdpClient7)rdp.GetOcx();
    // client.RemoteProgram2.RemoteProgramMode = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).DisplayConnectionBar = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).ConnectionBarShowPinButton = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).BitmapVirtualCache32BppSize = 48;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).ConnectionBarShowRestoreButton = false;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).ConnectionBarShowMinimizeButton = true;

((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).EnableWindowsKey = 1;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).GrabFocusOnConnect = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectDrives = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectClipboard = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectPrinters = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectPOSDevices = true;

rdp.Server = "1.2.3.4";
rdp.UserName = "Rmlabuser2";
IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
secured.ClearTextPassword = "Rmlabuser2";
// rdp.FullScreenTitle = "Full Screen";
// rdp.SecuredSettings.FullScreen = 1;
// rdp.SecuredSettings.StartProgram = "calc";
rdp.Connect();

我再说一遍,按键有效,我无法按回车。

感谢。

1 个答案:

答案 0 :(得分:0)

You could try P/Invoking Windows's keybd_event method instead.

[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,
int dwExtraInfo);

const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
const uint KEYEVENTF_KEYUP = 0x0002;

Then when you want to press it:

keybd_event((byte)System.Windows.Forms.Keys.Enter, 0x45, KEYEVENTF_EXTENDEDKEY, 0); //Key down
keybd_event((byte)System.Windows.Forms.Keys.Enter, 0x45, KEYEVENTF_EXTENDEDKEY |KEYEVENTF_KEYUP, 0); //Key up