Skip to content

Instantly share code, notes, and snippets.

@KOZ60
Last active October 30, 2023 16:35
Show Gist options
  • Save KOZ60/66c404eec30cf97417a04eed00d52958 to your computer and use it in GitHub Desktop.
Save KOZ60/66c404eec30cf97417a04eed00d52958 to your computer and use it in GitHub Desktop.
Aspect Form
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class Form1 : Form
{
private int ncHeight;
private int ncWidth;
private int hitTest;
private double aspect = 0;
public Form1() {
InitializeComponent();
}
protected override void OnCreateControl() {
base.OnCreateControl();
var cs = ClientSize;
aspect = (double)cs.Width / cs.Height;
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
var cs = ClientSize;
ncHeight = Height - cs.Height;
ncWidth = Width - cs.Width;
}
protected override void WndProc(ref Message m) {
switch (m.Msg) {
case WM_NCHITTEST:
WmNcHitTest(ref m);
break;
case WM_WINDOWPOSCHANGING:
WmWindowPosChanging(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
private void WmNcHitTest(ref Message m) {
base.WndProc(ref m);
hitTest = m.Result.ToInt32();
}
private void WmWindowPosChanging(ref Message m) {
if (aspect != 0) {
var wp = (WINDOWPOS)m.GetLParam(typeof(WINDOWPOS));
if ((wp.flags & SWP_NOSIZE) == 0) {
switch (hitTest) {
case HTTOP:
case HTBOTTOM:
wp.cx = (int)((wp.cy - ncHeight) * aspect) + ncWidth;
break;
default:
wp.cy = (int)((wp.cx - ncWidth) / aspect) + ncHeight;
break;
}
Marshal.StructureToPtr(wp, m.LParam, false);
}
}
}
private const int WM_WINDOWPOSCHANGING = 0x0046;
private const int WM_NCHITTEST = 0x0084;
private const int SWP_NOSIZE = 0x0001;
private const int HTTOP = 12;
private const int HTBOTTOM = 15;
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPOS
{
public IntPtr hwnd;
public IntPtr hwndInsertAfter;
public int x;
public int y;
public int cx;
public int cy;
public int flags;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment