错误属性' 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不存在。
答案 0 :(得分:5)
您必须在没有正文的方法声明中应用[DllImport]
属性,并带有static extern
修饰符。
您可以在需要时查找translated function declarations on PInvoke.net,包括相关结构。您需要的函数FindWindow
如下所示:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);