不使用Windows窗体应用程序,可以在屏幕上创建一个大的白色矩形吗?
如果可能的话,矩形应覆盖整个屏幕。
我知道必须使用System.Drawing
,并尝试了几个步骤,但实际上没有在我的屏幕上打印任何内容!
您需要使用System.Drawing
和System.Runtime.InteropServices
。您可能需要将它们添加到项目引用中。
using System.Runtime.InteropServices;
using System.Drawing;
使用P/Invoke将方法添加到您的类中
[DllImport("User32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
public static extern void ReleaseDC(IntPtr hwnd, IntPtr dc);
获取整个屏幕的Graphics
对象,并在其上绘制一个矩形:
IntPtr desktopPtr = GetDC(IntPtr.Zero);
Graphics g = Graphics.FromHdc(desktopPtr);
SolidBrush b = new SolidBrush(Color.White);
g.FillRectangle(b, new Rectangle(0, 0, 1920, 1080));
g.Dispose();
ReleaseDC(IntPtr.Zero, desktopPtr);
这种方法的问题在于,如果屏幕有任何刷新,矩形就会被覆盖,使其对大多数实际应用程序无用。
和之前一样,您需要一个项目引用。这次是 System.Windows.Forms
。您还需要再次使用 System.Drawing
:
using System.Drawing;
using System.Windows.Forms;
制作一个新的表单,去除其边框,将其充满屏幕,并将其置于任务栏之上:
Form f = new Form();
f.BackColor = Color.White;
f.FormBorderStyle = FormBorderStyle.None;
f.Bounds = Screen.PrimaryScreen.Bounds;
f.TopMost = true;
Application.EnableVisualStyles();
Application.Run(f);
这可能存在问题,因为用户可以轻松地通过alt+tab从窗口切换到其他应用。如果您想执行任何更复杂的图形操作,则需要编写一些绘图代码,例如此处所示。要使表单背景透明,请将其TransparentKey
设置为与BackColor
相同。
我刚在.NET 4.5和Windows 7中测试了这两个功能,所以在早期版本中可能会有所不同。更多信息请参见此处和此处。
GetDC(0)
返回所有监视器的 DC。也许这可以解决你的问题:https://stackoverflow.com/a/53334112/1303323 - Stelios Adamantidis是的,可以在屏幕上绘制内容,但使用一个最上层的无边框窗体可能更容易。
如果必须要在控制台应用程序中实现此功能,也可以通过引用必要的程序集来完成,但这将导致控制台窗口在应用程序运行期间一直保留在屏幕上。
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
或者我认为您可以创建Window
的实例并在其中调用Show
。