如何在C#中导入GetAsyncKeyState?

如何在C#中导入GetAsyncKeyState?,c#,C#,要导入我正在使用的GetAsyncKeyState()API,请执行以下操作: [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vKey); 所有网页都提供相同的代码,但当我尝试编译编译器时,会抛出: 所需的类、委托、枚举、接口或结构 修饰符“extern”对此项无效 我直接使用命令行进行编译,但Visual C#也会抛出相同的错误。那么,导入函数的正确方法是什么呢?编译器引发的错误很明显。您应

要导入我正在使用的
GetAsyncKeyState()
API,请执行以下操作:

[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
所有网页都提供相同的代码,但当我尝试编译编译器时,会抛出:

所需的类、委托、枚举、接口或结构
修饰符“extern”对此项无效


我直接使用命令行进行编译,但Visual C#也会抛出相同的错误。那么,导入函数的正确方法是什么呢?

编译器引发的错误很明显。您应该将该声明放在类中:

namespace MyNameSpace
{
   public class MyClass
   {
      [DllImport("user32.dll")]
      public static extern short GetAsyncKeyState(int vKey);
   }
}

您可以找到
extern
关键字的引用

,这意味着您将声明放在了错误的代码位置。它需要在类中,如下所示:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

// not here

namespace WindowsFormsApplication1
{

    // not here

    public partial class Form1 : Form
    {

        // put it INSIDE the class

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

        public Form1()
        {

            // not inside methods, though

            InitializeComponent();
        }

    }

}