Is there a .Net replacement for GetAsyncKeyState?

In VB6, I used the Windows API call GetAsyncKeyState to determine if the user had pressed the ESC key so that they could exit the long loop.

Declare Function GetAsyncKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer

Is there an equivalent in pure .NET that requires a direct API call?

+3
source share
2 answers

You can find the P / Invoke declaration for GetAsyncKeyState from http://pinvoke.net/default.aspx/user32/GetAsyncKeyState.html

Here's the C # signature, for example:

[DllImport("user32.dll")]
static extern short GetAsyncKeyState(int vKey);
+3
source

There are several options depending on your intended use, including calling the same method as described above). From the console application:

bool exitLoop = false;
for(int i=0;i<bigNumber && !exitLoop;i++)
{
    // Do Stuff.
    if(Console.KeyAvailable)
    {
        // Read the key and display it (false to hide it)
        ConsoleKeyInfo key = Console.ReadKey(true);
        if(ConsoleKey.Escape == key.Key)
        {
            exitLoop=false;
        }
    }
}

Windows, , ( ):

public partial class Form1 : Form
{
    private bool exitLoop;
    public Form1()
    {
        InitializeComponent();
        this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyUp);
    }
    public void doSomething()
    {
        // reset our exit flag:
        this.exitLoop = false;
        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(delegate(object notUsed)
            {
                while (!exitLoop)
                {
                    // Do something
                }
            }));
    }
    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        if (Keys.Escape == e.KeyCode)
        {
            e.Handled = true;
            this.exitLoop = true;
        }
    }

}

, - - . , , ThreadPool . , , , , . - , , ...

public override bool PreProcessMessage(ref Message msg)
{
  // Handle the message or pass it to the default handler...
  base.PreProcessMessage(msg);
}
+1

Source: https://habr.com/ru/post/1697517/


All Articles