Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a low level window class #3010

Merged
merged 2 commits into from
Mar 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\System.Windows.Forms.Primitives\src\System.Windows.Forms.Primitives.csproj" />
<ProjectReference Include="..\..\..\System.Windows.Forms\src\System.Windows.Forms.csproj" />
</ItemGroup>

Expand Down
12 changes: 12 additions & 0 deletions src/Common/tests/InternalUtilitiesForTests/InternalsVisibleTo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Runtime.CompilerServices;

// Awkward, but necessary to expose Interop based internals to other test libaries
[assembly: InternalsVisibleTo("System.Windows.Forms.Primitives.Tests, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Windows.Forms.Tests, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Windows.Forms.Design.Tests, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("WinformsControlsTest, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("MauiListViewTests, PublicKey=00000000000000000400000000000000")]
203 changes: 203 additions & 0 deletions src/Common/tests/InternalUtilitiesForTests/src/WindowClass.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using static Interop;

namespace System
{
internal class WindowClass
{
[DllImport(Libraries.User32, SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
public unsafe static extern IntPtr LoadIconW(
IntPtr hInstance,
IntPtr lpIconName);

private const int CW_USEDEFAULT = unchecked((int)0x80000000);
private const uint IDI_APPLICATION = 32512;
private const uint IDC_ARROW = 32512;
private const int COLOR_WINDOW = 5;

private static RECT DefaultBounds => new RECT(CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT);

// Stash the delegate to keep it from being collected
private readonly User32.WNDPROC _windowProcedure;
private User32.WNDCLASS _wndClass;
private readonly string _className;
private readonly string _menuName;

public ushort Atom { get; private set; }
public IntPtr MainWindow { get; private set; }
public IntPtr ModuleInstance { get; }

/// <summary>
/// Constructor.
/// </summary>
/// <param name="className">Name, or default will be generated.</param>
/// <param name="moduleInstance">Module to associate with the window. The entry assembly is the default.</param>
/// <param name="backgroundBrush">Use (IntPtr)(-1) for no background brush.</param>
/// <param name="icon">Use (IntPtr)(-1) for no icon.</param>
/// <param name="cursor">Use (IntPtr)(-1) for no cursor.</param>
/// <param name="menuName">Menu name, can not set with <paramref name="menuId"/>.</param>
/// <param name="menuId">Menu id, can not set with <paramref name="menuName"/>.</param>
public unsafe WindowClass(
string className = default,
IntPtr moduleInstance = default,
User32.CS classStyle = User32.CS.HREDRAW | User32.CS.VREDRAW,
IntPtr backgroundBrush = default,
IntPtr icon = default,
IntPtr cursor = default,
string menuName = null,
int menuId = 0,
int classExtraBytes = 0,
int windowExtraBytes = 0)
{
// Handle default values
className ??= Guid.NewGuid().ToString();

if (backgroundBrush == default)
{
backgroundBrush = User32.GetSysColorBrush(COLOR_WINDOW);
}
else if (backgroundBrush == (IntPtr)(-1))
{
backgroundBrush = default;
}

if (icon == default)
{
icon = LoadIconW(IntPtr.Zero, (IntPtr)IDI_APPLICATION);
}
else if (icon == (IntPtr)(-1))
{
icon = default;
}

if (cursor == default)
{
cursor = User32.LoadCursorW(IntPtr.Zero, (IntPtr)User32.CursorResourceId.IDC_ARROW);
}
else if (cursor == (IntPtr)(-1))
{
cursor = default;
}

if (moduleInstance == IntPtr.Zero)
Marshal.GetHINSTANCE(Assembly.GetCallingAssembly().Modules.First());

if (menuId != 0 && menuName != null)
throw new ArgumentException($"Can't set both {nameof(menuName)} and {nameof(menuId)}.");

_windowProcedure = WNDPROC;
ModuleInstance = moduleInstance;

_className = className;
_menuName = menuName ?? string.Empty;

_wndClass = new User32.WNDCLASS
{
style = classStyle,
lpfnWndProc = Marshal.GetFunctionPointerForDelegate(_windowProcedure),
cbClsExtra = classExtraBytes,
cbWndExtra = windowExtraBytes,
hInstance = moduleInstance,
hIcon = icon,
hCursor = cursor,
hbrBackground = backgroundBrush,
lpszMenuName = (char*)menuId
};
}

public bool IsRegistered => Atom != 0;

public unsafe WindowClass Register()
{
fixed (char* name = _className)
fixed (char* menuName = _menuName)
{
_wndClass.lpszClassName = name;
if (!string.IsNullOrEmpty(_menuName))
_wndClass.lpszMenuName = menuName;

ushort atom = User32.RegisterClassW(ref _wndClass);
if (atom == 0)
{
throw new Win32Exception();
}
Atom = atom;
return this;
}
}

public IntPtr CreateWindow(
string windowName = null,
User32.WS style = User32.WS.OVERLAPPED,
User32.WS_EX extendedStyle = default,
bool isMainWindow = false,
IntPtr parentWindow = default,
IntPtr parameters = default,
IntPtr menuHandle = default)
{
return CreateWindow(
DefaultBounds,
windowName,
style,
extendedStyle,
isMainWindow,
parentWindow,
parameters,
menuHandle);
}

public unsafe IntPtr CreateWindow(
RECT bounds,
string windowName = null,
User32.WS style = User32.WS.OVERLAPPED,
User32.WS_EX extendedStyle = default,
bool isMainWindow = false,
IntPtr parentWindow = default,
IntPtr parameters = default,
IntPtr menuHandle = default)
{
if (!IsRegistered)
throw new ArgumentException("Window class must be registered before using.");

IntPtr window = User32.CreateWindowExW(
dwExStyle: extendedStyle,
lpClassName: (char*)Atom,
lpWindowName: windowName,
dwStyle: style,
X: bounds.X,
Y: bounds.Y,
nWidth: bounds.Width,
nHeight: bounds.Height,
hWndParent: parentWindow,
hMenu: menuHandle,
hInst: IntPtr.Zero,
lpParam: parameters);

if (isMainWindow)
MainWindow = window;

return window;
}

protected virtual IntPtr WNDPROC(IntPtr hWnd, User32.WM msg, IntPtr wParam, IntPtr lParam)
{
switch (msg)
{
case User32.WM.DESTROY:
if (hWnd == MainWindow)
User32.PostQuitMessage(0);
return (IntPtr)0;
}

return User32.DefWindowProcW(hWnd, msg, wParam, lParam);
}
}
}
12 changes: 11 additions & 1 deletion src/System.Windows.Forms.Primitives/src/Interop/Interop.RECT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,17 @@ public static implicit operator Rectangle(RECT r)
public static implicit operator RECT(Rectangle r)
=> new RECT(r);

public int X => left;

public int Y => top;

public int Width
=> right - left;

public int Height
=> bottom - top;

public Size Size
=> new Size(right - left, bottom - top);
=> new Size(Width, Height);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ internal static partial class User32
[Flags]
public enum CS : uint
{
VREDRAW = 0x0001,
HREDRAW = 0x0002,
DBLCLKS = 0x0008,
DROPSHADOW = 0x00020000,
SAVEBITS = 0x0800
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ internal static partial class Interop
internal static partial class User32
{
[DllImport(Libraries.User32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateWindowExW(
int dwExStyle,
string lpClassName,
public unsafe static extern IntPtr CreateWindowExW(
WS_EX dwExStyle,
char* lpClassName,
string lpWindowName,
RussKie marked this conversation as resolved.
Show resolved Hide resolved
int dwStyle,
WS dwStyle,
int X,
int Y,
int nWidth,
Expand All @@ -23,5 +23,25 @@ public static extern IntPtr CreateWindowExW(
IntPtr hMenu,
IntPtr hInst,
[MarshalAs(UnmanagedType.AsAny)] object lpParam);

public unsafe static IntPtr CreateWindowExW(
WS_EX dwExStyle,
string lpClassName,
string lpWindowName,
WS dwStyle,
int X,
int Y,
int nWidth,
int nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInst,
object lpParam)
{
fixed(char* c = lpClassName)
{
return CreateWindowExW(dwExStyle, c, lpWindowName, dwStyle, X, Y, nWidth, nHeight, hWndParent, hMenu, hInst, lpParam);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ internal static partial class Interop
{
internal static partial class User32
{
// The Cursor class has an IntPtr constructor that takes a handle
// to an existing cursor. The int constructor does the LoadCursorW
// call. To avoid accidental use of the IntPtr constructor this
// set of defines should be left as int, even though they ultimately
// need converted to IntPtr.
public static class CursorResourceId
{
public const int IDC_ARROW = 32512;
Expand All @@ -28,6 +33,6 @@ public static class CursorResourceId
}

[DllImport(Libraries.User32, ExactSpelling = true)]
public static extern IntPtr LoadCursorW(IntPtr hInst, int iconId);
public static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName);
}
}
Loading