简体   繁体   中英

What is the C# equivalent of Declare Function in VB.NET?

I am trying to convert this VB.NET code to C#:

Private Declare Function GetKeyPress Lib "user32" Alias "GetAsyncKeyState" (ByVal key As Integer) As Integer

How would I go about doing that? I simply can't find the equivalent of Declare Function . Maybe I would have but the Telerik Code Converter says that its equivalent doesn't exist.

Any help will be much appreciated. Thanks in advance.

You should use the DllImport attribute.

class Program
{

    [DllImport(@"user32.dll")]
    static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);

    static void Main(string[] args)
    {
        // Do whatever you want here...
    }
}

From MSDN

Sometimes you need to call a procedure defined in a file (such as a DLL or code resource) outside your project. When you do this, the Visual Basic compiler does not have access to the information it needs to call the procedure correctly, such as where the procedure is located, how it is identified, its calling sequence and return type, and the string character set it uses. The Declare statement creates a reference to an external procedure and supplies this necessary information.

So in C# you'll have use DllImportAttribute Class as

[DllImport("user32.dll")]
static extern int GetAsyncKeyState(int key);
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM