C#で[DllImport("")]を使用するにはどうすればいいですか? 質問する

C#で[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?

何かアイデアはありますか? どうすればいいでしょうか? よろしくお願いします。

ベストアンサー1

メソッド内でローカル メソッドを宣言したり、属性を持つ他のメソッドを宣言したりすることはできません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;
    }
}

おすすめ記事