[英]I'm trying to use dll import in my new class but getting error Attribute 'DllImport' is not valid on this declaration type
The error Attribute 'DllImport' is not valid on this declaration type. 错误属性“ DllImport”在此声明类型上无效。 It is only valid on 'method' declarations.
它仅对“方法”声明有效。 Tried to add the dll import before the class in a method but same error.
试图在方法中添加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不存在。
You must apply the [DllImport]
attribute on a method declaration without a body, bearing the static extern
modifiers. 您必须将
[DllImport]
属性应用到没有主体的方法声明中,并带有static extern
修饰符。
You can look up translated function declarations on PInvoke.net , including relevant structures when required. 您可以在PInvoke.net上查找翻译后的函数声明 ,包括所需的相关结构。 The function
FindWindow
, which you require, looks like this: 您需要的功能
FindWindow
如下所示:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.