Skip to content

Commit

Permalink
Disable WinFormsAvaloniaControlHost in design mode (#16296)
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-lerch authored Jul 12, 2024
1 parent ab02e25 commit 671a13d
Showing 1 changed file with 32 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Avalonia.Controls.Embedding;
using Avalonia.Win32.Interop;
Expand Down Expand Up @@ -49,15 +51,20 @@ public AvControl? Content
/// <inheritdoc />
protected override void OnHandleCreated(EventArgs e)
{
_root = new();
_root.Content = _content;
_root.Prepare();
_root.StartRendering();
_root.GotFocus += RootGotFocus;
// EmbeddableControlRoot requires Avalonia to be initialized which is not done by the Windows Forms designer.
if (!DesignMode)
{
_root = new();
_root.Content = _content;
_root.Prepare();
_root.StartRendering();
_root.GotFocus += RootGotFocus;

FixPosition();

UnmanagedMethods.SetParent(WindowHandle, Handle);
}

FixPosition();

UnmanagedMethods.SetParent(WindowHandle, Handle);
base.OnHandleCreated(e);
}

Expand Down Expand Up @@ -93,14 +100,14 @@ protected override void OnGotFocus(EventArgs e)
if (handle != default)
UnmanagedMethods.SetFocus(handle);
}

private void FixPosition()
{
var handle = WindowHandle;
if (handle != default && Width > 0 && Height > 0)
UnmanagedMethods.MoveWindow(handle, 0, 0, Width, Height, true);
}

/// <inheritdoc />
protected override void OnResize(EventArgs e)
{
Expand All @@ -111,6 +118,21 @@ protected override void OnResize(EventArgs e)
/// <inheritdoc />
protected override void OnPaint(PaintEventArgs e)
{
if (DesignMode)
{
const string message = "Avalonia control is disabled in design mode.";

using var pen = new Pen(SystemBrushes.ControlDark);
var outline = ClientSize - new SizeF(pen.Width, pen.Width);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.DrawRectangle(pen, 0, 0, outline.Width, outline.Height);
e.Graphics.DrawLine(pen, 0, 0, outline.Width, outline.Height);
e.Graphics.DrawLine(pen, 0, outline.Height, outline.Width, 0);

var messageSize = e.Graphics.MeasureString(message, Font, ClientSize);
var messageLocation = new PointF(ClientSize.Width / 2 - messageSize.Width / 2, ClientSize.Height / 2 - messageSize.Height / 2);
var messageArea = new RectangleF(messageLocation, messageSize);
e.Graphics.DrawString(message, Font, SystemBrushes.ControlText, messageArea);
}
}
}

0 comments on commit 671a13d

Please sign in to comment.