问题描述
是否可以在不使用表单应用程序的情况下在屏幕上创建一个大的白色矩形?
Is it possible to create a big white rectangle on the screen, without using a Forms Application?
如果可能,它应该覆盖整个屏幕.我知道我必须使用 System.Drawing
并尝试了几个步骤,但实际上都没有在我的屏幕上打印任何内容!
It should cover the whole screen if possible.
I know I have to use the System.Drawing
and tried several steps, but none have actually printed anything to my screen!
推荐答案
方法一:调用Windows API
您需要 System.Drawing
和 System.Runtime.InteropServices
.您可能需要向它们添加项目引用.
Method 1: Call the Windows API
You need System.Drawing
and System.Runtime.InteropServices
. You may need to add project references to them.
using System.Runtime.InteropServices;
using System.Drawing;
使用 P/Invoke 将方法添加到您的类中
Add the methods to your class with 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
对象并用它画一个矩形:
Get a Graphics
object for the entire screen and draw a rectangle with it:
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);
这种方法的问题是,如果屏幕完全刷新,矩形就会被覆盖,这对于大多数实际应用来说毫无用处.
The problem with this method is that if the screen refreshes at all, the rectangle will be overwritten, making it useless for most practical applications.
和以前一样,您需要一个项目参考.这次是 System.Windows.Forms
.您还需要 System.Drawing
再次:
As before, you need a project reference. This time to System.Windows.Forms
. You'll also need System.Drawing
again:
using System.Drawing;
using System.Windows.Forms;
制作新的表单,去掉它的边框,用它填满屏幕,然后把它放在任务栏的顶部:
Make the new form, remove its borders, fill the screen with it, and put it on top of the taskbar:
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
相同.
A possible issue with this is that the user can just alt+tab away from the window. If you want to do any more complicated graphics, you'll need to write some drawing code like this. To make the form background transparent, set its TransparentKey
to the same as its Backolor
.
我刚刚在 .NET 4.5 和 Windows 7 中测试了这两个版本,因此早期版本可能会有所不同.更多信息这里和这里.
I've just tested both of these in .NET 4.5 and Windows 7, so it may be different for earlier versions. More information here and here.
这篇关于在没有表格的情况下在屏幕上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!