【发布时间】:2014-10-28 13:59:10
【问题描述】:
在下面的代码中,为什么user32会报错?
我认为通过在方法主体上方添加[DllImport("user32.dll", CharSet = CharSet.Unicode)],然后我可以做出类似user32.IsWindowVisible(hWnd) 这样的语句,但是该代码行的user32 部分会导致错误。
这是一个完整的例子。如果您将其复制粘贴到 Visual Studio 的类文件中,您将看到错误:
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System;
using System.Text;
namespace Pinvoke.Automation.Debug.Examples
{
internal static class ExampleEnumDesktopWindows
{
public delegate bool EnumDelegate(IntPtr hWnd, int lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "GetWindowText",
ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount);
[DllImport("user32.dll", EntryPoint = "EnumDesktopWindows",
ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static void DoExample()
{
var collection = new List<string>();
user32.EnumDelegate filter = delegate(IntPtr hWnd, int lParam)
{
StringBuilder strbTitle = new StringBuilder(255);
int nLength = user32.GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1);
string strTitle = strbTitle.ToString();
if (user32.IsWindowVisible(hWnd) && string.IsNullOrEmpty(strTitle) == false)
{
collection.Add(strTitle);
}
return true;
};
if (user32.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero))
{
foreach (var item in collection)
{
Console.WriteLine(item);
}
}
Console.Read();
}
}
}
【问题讨论】:
-
“为什么 user32 会导致错误” ... 哪个错误?请明确点;我们看不到你的显示器。
-
“我认为通过在方法主体上方添加 [DllImport...],我可以做出类似 user32.IsWindowVisible(hWnd) 的语句” - 不,这根本不是它的工作原理。你已经声明了你的外部,直接引用它们。他们根本不需要
user32.。 -
而且在非外部方法上添加
[DllImport]是没有意义的。