2016-06-16 6 views
-1

私は次のPowerShellスクリプトを使用して、メモ帳のGETウィンドウをしようとしています:のFindWindowメソッドのエラー

$pinvokes = @' 
    [DllImport("user32.dll", CharSet=CharSet.Auto)] 
    public static extern IntPtr Connect(string className, string Notepad); 

    [DllImport("user32.dll")] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    public static extern bool SetForegroundWindow(IntPtr hWnd); 
'@ 

Add-Type -AssemblyName System.Windows.Forms 
Add-Type -MemberDefinition $pinvokes -Name NativeMethods -Namespace MyUtils 
$hwnd = [MyUtils.NativeMethods]::FindWindow($null, "Notepad") 

しかし、私はFindWindow()を使用するとき、私は下のエラーを取得しています:あなたが持っていない

Method invocation failed because [MyUtils.NativeMethods] doesn't contain a method named 'FindWindow'. 
At line:1 char:44 
+ $hwnd = [MyUtils.NativeMethods]::FindWindow <<<< ($null, "Notepad") 
    + CategoryInfo   : InvalidOperation: (FindWindow:String) [], RuntimeException 
    + FullyQualifiedErrorId : MethodNotFound
+1

コード列の輸出2つのメソッド: '接続()'と 'SetForegroundWindow()' $ pinvokesであなたの最後の方法。最初にエクスポートされなかったメソッド 'FindWindow()'を呼び出そうとしたときにエラーが発生することに驚いたのはなぜですか? –

答えて

2

$ pinvokes定義で "FindWindow"メソッドを指定しました。

[DllImport("user32.dll", SetLastError = true)] 
static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

例:

$pinvokes = @' 
[DllImport("user32.dll", CharSet=CharSet.Auto)] 
public static extern IntPtr Connect(string className, string Notepad); 

[DllImport("user32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)] 
public static extern bool SetForegroundWindow(IntPtr hWnd); 

[DllImport("user32.dll", SetLastError = true)] 
static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 
'@ 

Add-Type -AssemblyName System.Windows.Forms 
# Using Passthru for example to show you how to return type directly  
$t = Add-Type -MemberDefinition $pinvokes -Name NativeMethods -Namespace MyUtils -PassThru 
$hwnd = $t::FindWindow($null, "Notepad")