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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19450783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:01:42  来源:igfitidea点击:

How to use [DllImport("")] in C#?

c#processdllimport

提问by ThomasFey

I found a lot of questions about it, but no one explains how I can use this.

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

I have this:

我有这个:

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;
    }
}

Can someone help me to understand why it gives me an error on the DllImportline and on the public staticline?

有人可以帮我理解为什么它给我DllImport在线和在线的错误public static吗?

Does anyone have an idea, what can I do? Thank you.

有谁有想法,我能做什么?谢谢你。

采纳答案by vcsjones

You can't declare an externlocal method inside of a method, or any other method with an attribute. Move your DLL import into the class:

您不能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;
    }
}