如何在C#中使用[DllImport(“”)]?

时间:2013-10-18 13:22:23

标签: c# process dllimport

我发现了很多关于它的问题,但没有人解释我如何使用它。

我有这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.FSharp.Linq.RuntimeHelpers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;

public class WindowHandling
{
    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        [DllImport("User32.dll")]
        public static extern int SetForegroundWindow(IntPtr point);
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

有人可以帮助我理解为什么它会在DllImport行和public static行上给我一个错误吗?

有没有人有想法,我该怎么办? 谢谢。

2 个答案:

答案 0 :(得分:61)

您不能在方法内部声明extern本地方法,也不能在属性中声明任何其他方法。将DLL导入移动到类中:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

答案 1 :(得分:1)

从 C# 9 开始,如果您从 public 减速中删除 SetForegroundWindow 关键字,您的语法将有效:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.FSharp.Linq.RuntimeHelpers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;

public class WindowHandling
{
    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        [DllImport("User32.dll")]
        static extern int SetForegroundWindow(IntPtr point);
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

在 C# 9 中局部函数可以有属性,见 here