Help regarding PINVOKE of the GetWindowRect

Hello,

I am learning PINVOKE and I took an example straight out of this Microsoft DevBlogs site (https://devblogs.microsoft.com/scripting/weekend-scripter-manage-window-placement-by-using-pinvoke/)

I am trying to figuring out why I keep getting the can not convert RECT error even though I follow the instructions from the example code. So I would like to seek any suggestion or recommendations on how to overcome the errors.

Thank you so much for all of the helps.

 

Attached is the sample code

@"

using System;

using System.Runtime.InteropServices;

public class Window {

[DllImport(“user32.dll”)]

[return: MarshalAs(UnmanagedType.Bool)]

public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

}

public struct RECT

{

public int Left; // x position of upper-left corner

public int Top; // y position of upper-left corner

public int Right; // x position of lower-right corner

public int Bottom; // y position of lower-right corner

}

"@

#window::GetWindowRect

$Handle = (Get-Process -Name audiodg).MainWindowHandle

$Rectangle = New-Object RECT

 

=========================================================

 

Attached below is the error message :

 

Exception calling “GetWindowRect” with “2” argument(s): “Cannot convert the “RECT” value of
type “RECT” to type “RECT”.”
At C:\Users\umktdm\Desktop\MinhPSScript\testnewp1.ps1:39 char:1

  • CategoryInfo : NotSpecified: (:slight_smile: [], MethodInvocationException
  • FullyQualifiedErrorId : PSInvalidCastException

 

 

 

I don’t exactly know of what I did that may eliminate the error message.

I just changed [Window]::GetWindowRect($Handle,[ref]$Rectangle) to [Win32]::GetWindowRect($Handle,[ref]$Rectangle) , and it gave me no error.