You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.7 KiB
85 lines
2.7 KiB
// Author: Gockner, Simon
|
|
// Created: 2021-04-07
|
|
// Copyright(c) 2021 SimonG. All Rights Reserved.
|
|
|
|
using System;
|
|
using System.ComponentModel;
|
|
using System.Runtime.InteropServices;
|
|
using Lib.NotifyIcon.Windows.Native.Types;
|
|
|
|
namespace Lib.NotifyIcon.Windows.Native
|
|
{
|
|
internal abstract class NativeWindow
|
|
{
|
|
private const uint WS_POPUP = 0x80000000;
|
|
|
|
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
|
|
private readonly WindowApi.WndProc _wndProc; //We need to store the window proc as a field so that it doesn't get garbage collected away
|
|
|
|
private readonly string _className = "NativeHelperWindow" + Guid.NewGuid();
|
|
|
|
/// <summary>
|
|
/// The window handle of the underlying native window
|
|
/// </summary>
|
|
public IntPtr Handle { get; }
|
|
|
|
/// <summary>
|
|
/// Creates a new native (Win32) helper window for receiving window messages
|
|
/// </summary>
|
|
protected NativeWindow()
|
|
{
|
|
_wndProc = WndProc;
|
|
|
|
WndClassEx wndClassEx = new()
|
|
{
|
|
cbSize = Marshal.SizeOf<WndClassEx>(),
|
|
lpfnWndProc = _wndProc,
|
|
hInstance = WindowApi.GetModuleHandle(null),
|
|
lpszClassName = _className
|
|
};
|
|
|
|
ushort atom = WindowApi.RegisterClassEx(ref wndClassEx);
|
|
|
|
if (atom == 0)
|
|
throw new Win32Exception();
|
|
|
|
Handle = WindowApi.CreateWindowEx(0, atom, null, WS_POPUP, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
|
|
|
if (Handle == IntPtr.Zero)
|
|
throw new Win32Exception();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Destructs the object and destroys the native window
|
|
/// </summary>
|
|
~NativeWindow()
|
|
{
|
|
if (Handle != IntPtr.Zero)
|
|
WindowApi.PostMessage(Handle, (uint) WindowsMessage.WmDestroy, IntPtr.Zero, IntPtr.Zero);
|
|
}
|
|
|
|
/// <summary>
|
|
/// This function will receive all the system window messages relevant to our window
|
|
/// </summary>
|
|
protected virtual IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
|
|
{
|
|
switch (msg)
|
|
{
|
|
case (uint) WindowsMessage.WmClose:
|
|
{
|
|
WindowApi.DestroyWindow(hWnd);
|
|
break;
|
|
}
|
|
case (uint) WindowsMessage.WmDestroy:
|
|
{
|
|
WindowApi.PostQuitMessage(0);
|
|
break;
|
|
}
|
|
default:
|
|
return WindowApi.DefWindowProc(hWnd, msg, wParam, lParam);
|
|
}
|
|
|
|
return IntPtr.Zero;
|
|
}
|
|
}
|
|
} |