我试图在我的新类中使用dll导入,但是在这个声明类型中获取错误属性'DllImport'是无效的

时间:2023-01-17 16:31:05

The error Attribute 'DllImport' is not valid on this declaration type. It is only valid on 'method' declarations. Tried to add the dll import before the class in a method but same error.

错误属性'DllImport'在此声明类型上无效。它只对“方法”声明有效。尝试在方法中在类之前添加dll导入,但同样错误。

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace MinimizeCapture
{

    class WatchForWindow
    {
        [DllImport("user32.dll")]
        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMINIMIZED = 2;
        private const int SW_SHOWMAXIMIZED = 3;

        private static ManagementEventWatcher watcher = null;

        public static void StartWatching()
        {
            WqlEventQuery query = new WqlEventQuery("Select * From __InstanceCreationEvent Within 2 Where TargetInstance Isa 'Win32_Process'");
            watcher = new ManagementEventWatcher(query);
            watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
            watcher.Start();
        }

        public static void StopWatching()
        {
            if (watcher != null)
            {
                watcher.Stop();
            }
        }

        private static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject obj = (ManagementBaseObject)e.NewEvent["TargetInstance"];
            string t = obj["Name"].ToString();
            GetHWND(t);
        }

        private static void GetHWND(string wName)
        {
            IntPtr hWnd = FindWindow("Notepad", "Untitled - Notepad");

        }
    }
}

The error is on this line:

错误在这一行:

[DllImport("user32.dll")]

I'm trying to use it since FindWindow is not exist.

我试图使用它,因为FindWindow不存在。

1 个解决方案

#1


5  

You must apply the [DllImport] attribute on a method declaration without a body, bearing the static extern modifiers.

您必须在没有正文的方法声明上应用[DllImport]属性,包含静态外部修饰符。

You can look up translated function declarations on PInvoke.net, including relevant structures when required. The function FindWindow, which you require, looks like this:

您可以在PInvoke.net上查找翻译后的函数声明,包括必要时的相关结构。您需要的函数FindWindow如下所示:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

#1


5  

You must apply the [DllImport] attribute on a method declaration without a body, bearing the static extern modifiers.

您必须在没有正文的方法声明上应用[DllImport]属性,包含静态外部修饰符。

You can look up translated function declarations on PInvoke.net, including relevant structures when required. The function FindWindow, which you require, looks like this:

您可以在PInvoke.net上查找翻译后的函数声明,包括必要时的相关结构。您需要的函数FindWindow如下所示:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);