Przyciąganie aplikacji do krawędzi okna

Zagadnienie: Chcemy aby okno po "dotknięciu" przykładowo lewej krawędzi okna powiększało i ustawiało sie na lewej stronie ekranu przylegając do jego krawędzi
Rozwiązanie: Dodajemy następujące linijki kodu:

Główna klasa

public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}
// Save original size
Size original;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool ReleaseCapture();


Form1_Load

original = this.Size;


Form1_MouseDown

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
// Drag to top to maximize
if (this.Location.Y {
this.WindowState = FormWindowState.Maximized;
}
else
{
this.Size = original;
}
// Drag to side to split screen
if (this.Location.X {
this.Location = new Point(0, 0);
this.Size = new Size(SystemInformation.WorkingArea.Width / 2, SystemInformation.WorkingArea.Height);
}
else if (this.Location.X >= SystemInformation.WorkingArea.Width / 2)
{
this.Location = new Point(SystemInformation.WorkingArea.Width / 2, 0);
this.Size = new Size(SystemInformation.WorkingArea.Width / 2, SystemInformation.WorkingArea.Height);
}
else
{
this.Size = original;
}
}
}

Źródło: https://stackoverflow.com/questions/63510530/borderless-form-drag-to-top...

Tags: