要导入我正在使用的GetAsyncKeyState()
API:
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
所有的网页都给了我相同的代码,但是当我尝试编译编译时抛出:
预期的课程,代表,枚举,界面或结构 修饰符'extern'对此项无效
我正在使用命令行直接编译,但Visual C#也会抛出相同的错误。那么导入函数的正确方法是什么?
答案 0 :(得分:6)
这意味着您将声明放在代码的错误位置。它必须是一个类,如下所示:
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();
}
}
}
答案 1 :(得分:4)
编译器引发的错误很明显。你应该把这个声明放在一个类中:
namespace MyNameSpace
{
public class MyClass
{
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
}
}
Here您可以找到extern
关键字