I have been able to get the following code to work and would like to understand more about STRUCT and New-Object.
If I move the STRUCT (MyRect) inside of the CLASS (MyClass), how would I reference it? Right now, it is as follow (outside of the CLASS and at the same level) and it is works.
$Rectangle = New-Object MyRECT
I have tried moving it inside the CLASS but it errored out. Most likely a Struct should always be at the same level as a Class right? Regardless, is there a proper way of declaring this?
$Rectangle = New-Object [MyClass]::MyRECT
If there is anything that you would like to point out, in terms of practices, please let me know, such as which of the two methods below is better to use? Thanks
clear-host
$code =
@'
using System;
using System.Runtime.InteropServices;
public class MyClass
{
[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, out MyRECT lpRect);
public static MyRECT Test3(int intHWND)
{
MyRECT TT = new MyRECT();
GetWindowRect((System.IntPtr) intHWND, out TT);
return TT;
}
}
public struct MyRECT
{
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
}
'@
Add-Type -TypeDefinition $Code
[Int]$HWND = (Get-Process -ID 9768).MainWindowHandle
$HWND
$oTest3 = [MyClass]::Test3($HWND)
$oTest3.Left
$oTest3.Top
$oTest3.Right
$oTest3.Bottom
$Rectangle = New-Object MyRECT
$null = [MyClass]::GetWindowRect([IntPtr]$HWND,[ref]$Rectangle)
$Rectangle.Left
$Rectangle.Top
$Rectangle.Right
$Rectangle.Bottom
MyRECTinside the class is perfectly legal, but it would make the type nameMyClass+MyRECT, which is then what you have to use in PowerShell (which is clumsy, but by design: you're mostly not expected to use nested types outside their declaring type). Despite how C# makes things appear,MyRECTdoes not in any way become a "member" of the class, it's just a scoping thing.MyClass+MyRECTworked. Thank You for providing that!