问题描述
我正在尝试制作一个C#应用程序,它将控制游戏.例如,我要执行的操作:按住A键150毫秒,按住左箭头500毫秒,依此类推.我进行了很多搜索,发现以下代码.我的程序首先针对游戏,然后按住键.
I'm trying to make a C# application, which is going to control a game. That I'm trying to do is for example: Hold key A for 150ms, Hold left arrow for 500ms and so on.I was searching a lot and I found the following code. My program firstly target the game and then holding the keys.
I'm holding the keys this way:
Keyboard.HoldKey(Keys.Left);
Thread.sleep(500);
Keyboard.ReleaseKey(Keys.Left);
这是键盘类:
public class Keyboard
{
public Keyboard()
{
}
[StructLayout(LayoutKind.Explicit, Size = 28)]
public struct Input
{
[FieldOffset(0)]
public uint type;
[FieldOffset(4)]
public KeyboardInput ki;
}
public struct KeyboardInput
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public long time;
public uint dwExtraInfo;
}
const int KEYEVENTF_KEYUP = 0x0002;
const int INPUT_KEYBOARD = 1;
[DllImport("user32.dll")]
public static extern int SendInput(uint cInputs, ref Input inputs, int cbSize);
[DllImport("user32.dll")]
static extern short GetKeyState(int nVirtKey);
[DllImport("user32.dll")]
static extern ushort MapVirtualKey(int wCode, int wMapType);
public static bool IsKeyDown(Keys key)
{
return (GetKeyState((int)key) & -128) == -128;
}
public static void HoldKey(Keys vk)
{
ushort nScan = MapVirtualKey((ushort)vk, 0);
Input input = new Input();
input.type = INPUT_KEYBOARD;
input.ki.wVk = (ushort)vk;
input.ki.wScan = nScan;
input.ki.dwFlags = 0;
input.ki.time = 0;
input.ki.dwExtraInfo = 0;
SendInput(1, ref input, Marshal.SizeOf(input)).ToString();
}
public static void ReleaseKey(Keys vk)
{
ushort nScan = MapVirtualKey((ushort)vk, 0);
Input input = new Input();
input.type = INPUT_KEYBOARD;
input.ki.wVk = (ushort)vk;
input.ki.wScan = nScan;
input.ki.dwFlags = KEYEVENTF_KEYUP;
input.ki.time = 0;
input.ki.dwExtraInfo = 0;
SendInput(1, ref input, Marshal.SizeOf(input));
}
public static void PressKey(Keys vk)
{
HoldKey(vk);
ReleaseKey(vk);
}
}
及其可在记事本/浏览器等中使用,但无论在全屏或窗口模式下,它均不适用于任何游戏.您能帮我弄清楚如何在全屏应用程序/游戏中按住键吗?谢谢!
and its working in notepad/browser etc, but it IS NOT working in any game, no matter fullscreen or window mode.Can you help me to figure out how I can hold keys in full screen apps/games?Thanks!
推荐答案
我是通过Windown API和SendInput方法实现的.
I did it with Windown API and SendInput method.
这篇关于游戏应用程序中的C#按住键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!