Reputation: 77
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
Upvotes: 1
Views: 322
Reputation: 77
Thanks to Jeroen Mostert, I am now able to move the STRUCT inside the class and reference it in PowerShell as:
$Rectangle = New-Object MyClass+MyRECT
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 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
}
public static MyRECT Test3(int intHWND)
{
MyRECT TT = new MyRECT();
GetWindowRect((System.IntPtr) intHWND, out TT);
return TT;
}
}
'@
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 MyClass+MyRECT
$null = [MyClass]::GetWindowRect([IntPtr]$HWND,[ref]$Rectangle)
$Rectangle.Left
$Rectangle.Top
$Rectangle.Right
$Rectangle.Bottom
Upvotes: 1