2014-09-03 43 views
0

在下面的代碼中,爲什麼user32會導致錯誤?在靜態方法中使用user32.dll的正確語法是什麼?

我認爲通過在方法主體上面添加[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(); 
     } 
    } 
} 
+1

*「爲什麼user32導致錯誤」* ...哪個錯誤?請明確點;我們看不到你的顯示器。 – cdhowie 2014-09-03 23:09:17

+2

「我認爲通過在方法主體上面添加[DllImport ...],我就可以生成像user32.IsWindowVisible(hWnd)這樣的語句」 - 不,不是這樣。..你已經聲明瞭你的extern,只是直接引用他們。他們根本不需要'user32.'。 – Blorgbeard 2014-09-03 23:11:07

+1

在非extern方法中添加'[DllImport]'是沒有意義的。 – Blorgbeard 2014-09-03 23:11:33

回答

1

DllImport屬性必須在標記爲'static'和'extern'的方法上指定,因此您的DoExample()方法中不能包含它。

嘗試從該方法中刪除它,並刪除user32。來自您的DoExample()函數內部的方法調用。

+0

是的,這工作。謝謝。 – sapbucket 2014-09-03 23:39:23

2

的P/Invoke需要的DLL名稱和EntryPoint屬性,在屬性DllImport同時指定。

你的代碼不關心這些。它只是使用您在聲明DllImport註釋方法時使用的標識符。

在你的情況下,標識符是IsWindowVisible,並且完全限定名稱是Pinvoke.Automation.Debug.Examples.ExampleEnumDesktopWindows.IsWindowVisible

相關問題