Подтвердить что ты не робот

Как использовать [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?

Есть ли у кого-нибудь идея, что я могу сделать? Спасибо.

4b9b3361

Ответ 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;
    }
}