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

标签 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 行给我一个错误?

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

最佳答案

您不能在方法内部声明 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;
    }
}

关于c# - 如何在 C# 中使用 [DllImport ("")]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19450783/

相关文章:

c# - 是否存在具有 user32.dll 中的函数、类型和常量的预先存在的 .NET 程序集或 NuGet 程序包(或类似程序包)?

c# - 如何将对象列表从 C++ 传递到 C#?

java - Android 创建日历事件总是作为生日

c# - 使用 LINQ 根据字符串列表选择多个记录

c# - 函数和方法的区别

c - fgets 错误消息循环 - C 中的 Linux shell

c++ - 单击两次 listWidget 项目时 Qt 崩溃

c++ - 如何执行注入(inject)到进程中的应用程序

c# - ListView 组标题单击 - 在 Windows 7 中禁用全选

c++ - 使用 dllimport 代替 dllexport