【问题标题】:How to create an 1 pixel wide window using C# and WinForm如何使用 C# 和 WinForm 创建一个 1 像素宽的窗口
【发布时间】:2016-01-05 12:49:15
【问题描述】:

我想创建一个在桌面底角显示一个小窗口的应用程序。启动时,窗口应该非常小,理想情况下,宽度只有几个像素。

这是我以前做的代码:

public partial class DurationT64 : Form
{
    private Size fullSize;
    private Point fullPos;
    private Point compactPos;

    public DurationT64()
    {
        InitializeComponent();

        var workingArea = Screen.PrimaryScreen.WorkingArea;

        this.MinimumSize = new Size(0, this.Height);
        this.MaximumSize = new Size(this.Width, this.Height);

        // fullPos: the window location when it is in full size form.
        fullPos = new Point(workingArea.Right - this.Width, workingArea.Bottom - this.Height);
        this.Location = fullPos;
        // fullSize: the size of the windown when it is in full size form.
        fullSize = new Size(this.Width, this.Height);
        this.Size = fullSize;

        // compactPos: the window location when it is in compact size form.
        compactPos = new Point(workingArea.Right - 30, fullPos.Y);
        this.Width = 1;
        this.Location = compactPos;
    }
}

如您所见,在此示例中,我打算创建一个宽度仅为 1 像素的窗口,靠近主显示器的右边缘放置。

但是,我意识到窗口并没有我预期的那么小。它下降到 20 像素宽,但不小于这个值。请参考下面的屏幕截图,例如: an image shows that the window is wider than it suppose to be

我对这个问题进行了一些研究,并注意到 Zach Johnson (@zach-johnson) 在 2009 年提出了一个解决方案。这里是它的链接Overcome OS Imposed Windows Form Minimum Size Limit

但是,该链接中提出的其他方法(Zach 提出的拦截 WM_ 消息和@Ace 提出的 SetBoundsCore 方法)对我有用。

谁能给我一些解决这个问题的方法?如果可能的话,最好是纯粹基于 C#/Winform 的解决方案,不依赖原生 Win32 窗口消息循环。

非常感谢!

【问题讨论】:

  • 你试过this.MinimumSize = new Size(1, 1);吗?

标签: c# winforms user-interface window


【解决方案1】:

这是相当直截了当的,Winforms 确保窗口不能小于系统规定的最小窗口大小,在 .NET 中显示为SystemInformation.MinWindowTrackSize property。这是一个“安全”设置,它确保用户在调整窗口大小时不会使窗口太小,从而失去对它的控制。同样的考虑也适用于代码。

绕过这个限制不需要魔法,你需要做两件事:

  • 将 FormBorderStyle 属性设置为 None,这样用户就无法调整窗口大小。
  • 在创建窗口后设置大小。 Load 事件是最好的。

关于您现有代码的一些 cmets:小心修改 Width/Height/Size 属性,您在构造函数中做的太多,它无法正常工作。在构造函数中,它们还与窗口的实际大小不匹配。并且在具有高分辨率显示器的现代机器上根本不会接近,自动缩放以匹配视频适配器的 DPI 在今天很重要。您必须推迟到创建窗口并完成缩放,Load 事件是此类代码的合适位置。实际使用 Load 的少数原因之一。

请注意,您的 Location 属性计算不足,它没有考虑任务栏的位置。在我的机器上不行,我喜欢右边的任务栏。

最少复制:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.FormBorderStyle = FormBorderStyle.None;
    }
    protected override void OnLoad(EventArgs e) {
        this.Width = 1;
        base.OnLoad(e);
    }
}

请记住,您需要鹰眼才能在屏幕上找到它 :)

【讨论】:

  • 嗨,汉斯,非常感谢 1px windows 的解决方案。我非常感谢您指出我将尺寸/位置相关代码放在错误位置的错误。谢谢。
  • 如果您不想在 load 事件中更改大小,则在 Load 事件中更改表单的位置也可以让您获得在属性中指定的大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多