模拟Hyper-V虚拟机的鼠标/键盘事件

问题描述:

我正在运行Windows 10作为主机,并且在另一个Windows 10中运行Hyper-V虚拟机。我正在做的是写一个C#程序,它会每隔1秒点击一次鼠标按键,并最终从键盘发送一些按键,如'abc'。模拟Hyper-V虚拟机的鼠标/键盘事件

到目前为止,我尝试PostMessageWM_LBUTTONDOWN和UP与窗口句柄到超v窗口,mouse_event,但没有任何工作。 mouse_event在主机上工作正常,每隔1秒点击一次,但是一旦我将鼠标悬停在虚拟机上,它就不再点击了。

有没有一种方法来模拟主机中的点击和键盘按键,让VM对它做出反应?

+0

就在我读hyper v不让你 – BugFinder

是的,有一种方法可以通过Hyper-V的WMI界面(可以通过PowerShell与C#很好地集成)访问。 VirtualPCGuy有一个关于使用Hyper-V做这类事情的10篇博文系列(从2016年3月7日开始)。以下是他的代码示例(在PowerShell中),以了解您正在询问的具体内容。

Typing a String

$VMName = “Windows 10 Enterprise” 
$VMCS = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter “ElementName=’$($VMName)'” 
$keyboard = $VMCS.GetRelated(“Msvm_Keyboard”) 
$keyboard.TypeText(“Hello!”) | out-null 

Controlling the Mouse

$VMName = “Windows 10 Enterprise” 
$VMCS = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter “ElementName=’$($VMName)'” 
$mouse = $VMCS.GetRelated(“Msvm_SyntheticMouse”) 
$mouse.SetAbsolutePosition(300,450) | out-null 
$mouse.ClickButton(2) | out-null 

注:这只会在基本模式,而不是增强模式下工作。如果你对做更高级的东西感兴趣,我强烈推荐阅读整个系列。

免责声明:在微软的Hyper-V工程团队工作。