gpt4 book ai didi

c# - 如何使用 C# 和 WinForm 创建一个 1 像素宽的窗口

转载 作者:行者123 更新时间:2023-11-30 20:40:44 31 4
gpt4 key购买 nike

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

这是我用来做的代码:

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 且不依赖 native Win32 窗口消息循环的解决方案。

非常感谢!

最佳答案

这很简单,Winforms 确保窗口不能小于系统强加的最小窗口大小,显示为 SystemInformation.MinWindowTrackSize property。在.NET 中。这是一个“安全”设置,它确保用户在调整窗口大小时不会将窗口设置得太小,从而失去对窗口的控制。同样的考虑也适用于代码。

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

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

关于您现有代码的一些评论:修改 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);
}
}

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

关于c# - 如何使用 C# 和 WinForm 创建一个 1 像素宽的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33006617/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com