I'm试图在我的新类中使用dll导入,但得到错误属性'在此声明类型上无效
本文关键字:属性 错误 类型 无效 声明 dll 我的 新类中 导入 | 更新日期: 2023-09-27 18:19:23
错误属性'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");
}
}
}
错误在这一行:
[DllImport("user32.dll")]
我正在尝试使用它,因为FindWindow不存在
你必须在没有主体的方法声明中应用[DllImport]
属性,并带有static extern
修饰符。
您可以在PInvoke.net上查找已翻译的函数声明,包括必要时的相关结构。您需要的函数FindWindow
如下所示:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);