2014-09-03 2 views
0

다음 코드에서 user32은 오류를 발생시키는 이유는 무엇입니까?정적 메서드에서 user32.dll을 사용하기위한 적절한 구문은 무엇입니까?

[DllImport("user32.dll", CharSet = CharSet.Unicode)]을 메서드 본문 위에 추가하면 user32.IsWindowVisible(hWnd)과 같은 문을 만들 수 있지만 해당 코드 줄의 user32 부분에 오류가 발생한다고 생각했습니다.

다음은 전체 예제입니다. 클래스 파일에 비주얼 스튜디오에이에 붙여 복사하는 경우에는 오류가 표시됩니다

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

+2

"메소드 바디 위에 [DllImport ...]를 추가하여 user32.IsWindowVisible (hWnd)과 같은 명령문을 작성할 수 있다고 생각했습니다. - 아뇨, ​​전혀 작동하지 않습니다. 당신은 당신의 externs를 선언했습니다. 그냥 그들을 직접 참조하십시오. 그것들은'user32.'를 전혀 필요로하지 않습니다. – Blorgbeard

+1

그리고 non extern 메서드에'[DllImport]'를 추가하는 것은 의미가 없습니다. – Blorgbeard

답변

1

'static'및 'extern'으로 표시된 메서드에 DllImport 특성을 지정해야하므로 DoExample() 메서드에서 DllImport 특성을 지정할 수 없습니다.

해당 방법에서 제거하고 user32를 제거하십시오. DoExample() 함수 내부의 메서드 호출에서 가져옵니다.

+0

예, 그렇습니다. 고맙습니다. – sapbucket

2

P/호출은 DLL 이름과 EntryPoint 재산, 모두 DllImport 속성에 지정된 필요합니다.

코드는이 점에 대해 신경 쓰지 않습니다. DllImport-annotated 메서드를 선언 할 때 사용한 식별자를 사용합니다.

해당 경우 식별자는 IsWindowVisible이고 정규화 된 이름은 Pinvoke.Automation.Debug.Examples.ExampleEnumDesktopWindows.IsWindowVisible입니다.