Jak używać [DllImport ( "" )] w C#?

Znalazłem wiele pytań na ten temat, ale nikt nie wyjaśnia, jak mogę tego użyć.

Mam to:

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

Czy ktoś może mi pomóc zrozumieć, dlaczego daje mi błąd na linii DllImport i na linii public static?

Czy ktoś ma pomysł, co mogę zrobić? Dziękuję.
Author: Peter Hall, 2013-10-18

1 answers

Nie Można zadeklarować lokalnej metody extern wewnątrz metody, ani żadnej innej metody z atrybutem. Przenieś import DLL do klasy:

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;
    }
}
 54
Author: vcsjones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-22 13:51:12