如何从 kernel32 导入 Sleep 函数?

How to import Sleep function from kernel32?

我必须从我的 windows 表单应用程序导入 kernel32.dll 才能使用睡眠功能。 在 VB.net 中,我使用以下代码。

Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

如何在c#中进行转换?

Using System.Runtime.InteropServices;  

....

public class NativeMethods
{

    [DllImport("kernel32")]
    public static extern void Sleep(uint dwMilliseconds);
}

您可以看到PInvoke

的文档
[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);

// code added by g. sharp @ http://www.paradisim.net
public class MainApp
{
    [STAThread]
    public static void Main()
    {
        Sleep(U2000);  // pause for two seconds
        System.Threading.Thread.Sleep(2000); // does the same thing
    }
}

如果您愿意,您可以 p/invoke kernel32 中的函数,如其他答案所示。然而,这样做几乎肯定是错误的。从您的 Declare 语句的形式来看,我认为您的代码早于 .net。

在 .net 中你应该调用 Thread.Sleep。在平台提供所需功能的地方使用它。文档说:

This method calls the Sleep function from the Windows system APIs.

使用该平台总是更干净、更可取。仅当没有平台提供的方法来实现该功能时才使用 p/invoke。