如何在C#中使用GetAsyncKeyState?

问题描述 投票:1回答:3

我想知道如何使用它。...我想说的是,如果我单击向上和向右箭头(Form1_KeyDown事件),则timer1.Start();当我释放向上和向右箭头(Form1_KeyUp事件)时,timer1.Stop();

我已经导入了“ User32.dll”

using System.Runtime.InteropServices;

[DllImport("User32.dll")]
public static extern short GetAsyncKeyState(Keys ArrowKeys);

所以如何使用它...我看到了很多网站,但找不到它

c#
3个回答
0
投票

这里是使用方法

int keystroke;

byte[] result = BitConverter.GetBytes(GetAsyncKeyState(keystroke));

if (result[0] == 1)
    Console.Writeline("the key was pressed after the previous call to GetAsyncKeyState.")

if (result[1] == 0x80)
    Console.Writeline("The key is down");

0
投票

为您实施IMessageFilter,在向上/向右箭头切换时形成并跟踪:

public partial class form1 : Form, IMessageFilter 
{

    public form1()
    {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }

    private bool UpDepressed = false;
    private bool RightDepressed = false;

    private const int WM_KEYDOWN = 0x100;
    private const int WM_KEYUP = 0x101;

    public bool PreFilterMessage(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_KEYDOWN:
                if ((Keys)m.WParam == Keys.Up)
                {
                    UpDepressed = true;
                }
                else if ((Keys)m.WParam == Keys.Right)
                {
                    RightDepressed = true;
                }
                break;

            case WM_KEYUP:
                if ((Keys)m.WParam == Keys.Up)
                {
                    UpDepressed = false;
                }
                else if ((Keys)m.WParam == Keys.Right)
                {
                    RightDepressed = false;
                }
                break;
        }

        timer1.Enabled = (UpDepressed && RightDepressed);
        label1.Text = timer1.Enabled.ToString();

        return false;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        label2.Text = DateTime.Now.ToString("ffff");
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.