gpt4 book ai didi

c# - 从 Powershell 调用 user32.dll 中的 keybd_event

转载 作者:行者123 更新时间:2023-11-30 15:24:52 25 4
gpt4 key购买 nike

我试图阻止屏幕保护程序启动。我试过发送击键,但它们都需要按标题抓取一个窗口。如果桌面上没有打开的窗口,就没有东西可以抓取。

所以我找到了一些可能有用的东西,但我不是 C# 向导。它基于 Simulating a keypress AND keyrelease in another application?

下面的代码应该发送一个 1,但我遗漏了一些东西。在从 Powershell 调用新类型之前,我没有收到任何错误。在这个工作之后,我想让它发送一个 F15 来重置屏幕保护程序倒计时,但不修改屏幕上的东西。 (但我必须通过发送 1 来先抓取)

Add-Type @"
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
public static class PressKeyForMe
{
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

//public static void Main(string[] args)
public static void Main()
{
//This code will press and hold the '1' button for 3 secs, and then will release for 1 second
//VK_F15 0x7E
keybd_event((byte)0x31, (byte)0x02, 0, UIntPtr.Zero);
Thread.Sleep(3000);

keybd_event((byte)0x31, (byte)0x82, (uint)0x2, UIntPtr.Zero);
Thread.Sleep(1000);
}
}

}
"@
cls

#all of these give me: Unable to find type
[void] [PressKeyForMe]::Main()
[void] [ConsoleApplication1]::PressKeyForMe()
[void] [PressKeyForMe.Main]
[void] [ConsoleApplication1.Main]
[void] [ConsoleApplication1.PressKeyForMe]::Main()

最佳答案

似乎您在该类型定义中遗漏了一些 using 语句:

Add-Type @"
using System;
using System.Threading;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
public static class PressKeyForMe
{
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

//public static void Main(string[] args)
public static void Main()
{
//This code will press and hold the '1' button for 3 secs, and then will release for 1 second
//VK_F15 0x7E
keybd_event((byte)0x31, (byte)0x02, 0, UIntPtr.Zero);
Thread.Sleep(3000);

keybd_event((byte)0x31, (byte)0x82, (uint)0x2, UIntPtr.Zero);
Thread.Sleep(1000);
}
}

}
"@

这现在应该可以工作了:

[ConsoleApplication1.PressKeyForMe]::Main()

您还可以只添加方法并将自动生成的类型分配给变量:

$KeyPresser = Add-Type -MemberDefinition @"
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

public static void PressOne(int press, int release)
{
//This code will press and hold the '1' button for 3 secs, and then will release for 1 second
//VK_F15 0x7E
keybd_event((byte)0x31, (byte)0x02, 0, UIntPtr.Zero);
Thread.Sleep(press);

keybd_event((byte)0x31, (byte)0x82, (uint)0x2, UIntPtr.Zero);
Thread.Sleep(release);
}

public static void PressOne()
{
PressOne(3000, 1000);
}
"@ -Name PressKeyForMe -UsingNamespace System.Threading -PassThru

现在您可以在没有完整类型名称的情况下调用该方法:

PS C:\> $KeyPresser::PressOne() 
PS C:\> $KeyPresser::PressOne(400,120) # you really need to press 3 seconds?

关于c# - 从 Powershell 调用 user32.dll 中的 keybd_event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32190518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com