52

それについて多くの質問を見つけましたが、これをどのように使用できるかを誰も説明していません。

私はこれを持っています:

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か?

どうすればいいですか?ありがとうございました。

4

2 に答える 2

87

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;
    }
}
于 2013-10-18T13:24:27.927 に答える
2

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 では、ローカル関数は属性を持つことができます。こちらを参照してください

于 2021-03-24T13:16:43.720 に答える