Windows绘画模型可以很好地满足您的要求。它从前景(OnPaint)分离绘制背景(OnPaintBackground)。然而,这并不意味着你只能画一次背景并完成它。窗口表面失效会调用两者。这首先需要使抗锯齿效果正常工作,但它们只能在已知的背景色下看起来很好。
将其拖出并在OnPaintBackground()覆盖中绘制图像。您可以让Control通过指定BackgroundImage属性为您自动执行此操作。您可能需要将DoubleBuffer属性设置为true,以避免您在绘制背景时看到的闪烁,并暂时清除前景像素。如果需要更新前景,请调用Invalidate()。
要完成,你的幻想其实是可能的。您需要使用顶层分层窗口覆盖图像。使用TransparencyKey属性设置的表单很容易获得。这里是一个示例实现:
using System;
using System.Drawing;
using System.Windows.Forms;
class OverlayedPictureBox : PictureBox {
private Form mOverlay;
private bool mShown;
public event PaintEventHandler PaintOverlay;
public OverlayedPictureBox() {
mOverlay = new Form();
mOverlay.FormBorderStyle = FormBorderStyle.None;
mOverlay.TransparencyKey = mOverlay.BackColor = Color.Magenta;
mOverlay.ShowInTaskbar = false;
}
protected void OnPaintOverlay(PaintEventArgs e) {
// NOTE: override this or implement the PaintOverlay event
PaintEventHandler handler = PaintOverlay;
if (handler != null) handler(this, e);
}
public void RefreshOverlay() {
// NOTE: call this to force the overlay to be repainted
mOverlay.Invalidate();
}
protected override void Dispose(bool disposing) {
if (disposing) mOverlay.Dispose();
base.Dispose(disposing);
}
protected override void OnVisibleChanged(EventArgs e) {
if (!mShown && !this.DesignMode) {
Control parent = this.Parent;
while (!(parent is Form)) parent = parent.Parent;
parent.LocationChanged += new EventHandler(parent_LocationChanged);
mOverlay.Paint += new PaintEventHandler(mOverlay_Paint);
mOverlay.Show(parent);
mShown = true;
}
base.OnVisibleChanged(e);
}
protected override void OnLocationChanged(EventArgs e) {
mOverlay.Location = this.PointToScreen(Point.Empty);
base.OnLocationChanged(e);
}
protected override void OnSizeChanged(EventArgs e) {
mOverlay.Size = this.Size;
base.OnSizeChanged(e);
}
void parent_LocationChanged(object sender, EventArgs e) {
mOverlay.Location = this.PointToScreen(Point.Empty);
}
private void mOverlay_Paint(object sender, PaintEventArgs e) {
OnPaintOverlay(e);
}
}
一个有趣的工件:最小化窗体并重新恢复它看起来,呃,特殊。
这两个答案都很棒。我必须选择一个。 :-( – catfood 2010-01-05 15:29:36