如何在C#中使用GetAsyncKeyState?

时间:2015-09-14 16:54:22

标签: c#

我想知道如何使用它....我想说,如果我单击向上和向右箭头(Form1_KeyDown事件),那么timer1.Start(); 当我释放向上和向右箭头(Form1_KeyUp事件)然后释放timer1.Stop();

我已经导入了" User32.dll"

using System.Runtime.InteropServices;

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

所以如何使用它...我看到很多网站但是无法获得它

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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");
    }

}