我想在面板控件内部的一切上显示一个矩形图。到目前为止,我在面板控件中只有一个WebBrowser。如果我开始运行程序而不将WebBrowser添加到面板控件,那么我将能够看到矩形。但是,如果我将WebBrowser添加到面板控件,那么它将与我的矩形图形重叠。
如何创建一个矩形绘制面板控件的INSIDE,它将重叠所有内容? (总是在上面)
下面的代码将在面板控件内部绘制一个蓝色矩形。但它不会显示,因为该面板包含一个WebBrowser。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Graphics_Overlay
{
public partial class GraphicsOverlayForm : Form
{
public GraphicsOverlayForm()
{
InitializeComponent();
Panel panel = new Panel();
panel.Dock = DockStyle.Fill;
panel.Paint += panel_Paint;
WebBrowser webBrowser = new WebBrowser();
webBrowser.Dock = DockStyle.Fill;
webBrowser.Url = new Uri("http://stackoverflow.com/");
Controls.Add(panel);
// If I comment out the line below then I will
// be able to see my blue rectangle.
panel.Controls.Add(webBrowser);
}
private void panel_Paint(object sender, PaintEventArgs e)
{
ShowLineJoin(e);
}
private void ShowLineJoin(PaintEventArgs e)
{
// Create a new pen.
Pen skyBluePen = new Pen(Brushes.Blue);
// Set the pen's width.
skyBluePen.Width = 1;
// Set the LineJoin property.
skyBluePen.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel;
// Draw a rectangle.
e.Graphics.DrawRectangle(skyBluePen,
new Rectangle(0, 0, 200, 200));
//Dispose of the pen.
skyBluePen.Dispose();
}
}
}
答案 0 :(得分:0)
这是不可能的。如果将WebBrowser添加为面板的子控件,它将在面板的背景区域上显示。当然,Panel的背景区域是绘制蓝色矩形的位置。您的绘图仍然存在,WebBrowser控件正在其上显示。
我想到了三种可能的解决方案,这里没有特别的顺序列出:
只要您希望蓝色矩形(或Panel控件背景上绘制的任何内容)可见,请将WebBrowser控件的Visible
属性设置为false
。再次将WebBrowser.Visible设置为true
,以便可以使用WebBrowser控件。
不是将WebBrowser控件添加为Panel的子控件,而控件又是容器窗体的子控件,而是将Panel和WebBrowser控件添加为容器窗体的子控件。换句话说,展平层次结构。因为这会删除父子关系,所以现在可以更改控件的Z顺序,更改哪一个是可见的。使用SendToBack
和BringToFront
成员函数在WinForms中这是微不足道的。
创建一个 new 控件,其名称类似BlueRectangle
或DrawingSurface
或类似内容,继承自System.Windows.Forms.Control
。覆盖其OnPaint
事件并将您的绘图代码放在那里。将此控件类的实例作为子项添加到Panel控件。然后,实际上,您的Panel控件将有两个子控件:BlueRectangle
控件和WebBrowser
控件。如上所述,使用SendToBack
和BringToFront
更改Z顺序,在两者之间来回移动。
在一个不相关的说明中,您应该更喜欢using
语句,以确保自动处理实现IDisposable
的对象,而不是显式调用Dispose
方法。例如,像这样编写ShowLineJoin
方法:
private void ShowLineJoin(PaintEventArgs e)
{
// Create a new pen with the specified color and width.
using (Pen skyBluePen = new Pen(Brushes.Blue, 1))
{
// Set the LineJoin property.
skyBluePen.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel;
// Draw a rectangle.
e.Graphics.DrawRectangle(skyBluePen,
new Rectangle(0, 0, 200, 200));
}
}
更简单,更易读,更安全。