[英]Is there any way to draw a control on some other control in C#?
我想在它的覆盖绘制事件中绘制一些控件。 通过绘制我的意思是真正的绘图,而不是将控件放在另一个控件内。 有没有好办法呢?
尝试使用ControlPaint类上的静态方法。 绘制的控件可能不像GUI的其余部分那样被剥离,但效果将非常可信。 下面是我的一些代码的简化版本。 它覆盖了ownerstrall ListBox的DrawItem方法,使用ControlPaint.DrawButton方法使列表项看起来像按钮。
对于复选框,组合,甚至拖动句柄,该类有更多好东西。
protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index > -1)
{
String itemText = String.Format("{0}", this.Items.Count > 0 ? this.Items[e.Index] : this.Name);
//Snip
System.Windows.Forms.ControlPaint.DrawButton(e.Graphics, e.Bounds, ButtonState.Normal);
e.Graphics.DrawString(itemText, this.Font, SystemBrushes.ControlText, e.Bounds);
}
}
您可以使用控件的DrawToBitmap方法轻松完成此操作。 这是一个片段,它将创建一个Button并在相同大小的PictureBox上绘制它:
Button btn = new Button();
btn.Text = "Hey!";
Bitmap bmp = new Bitmap(btn.Width, btn.Height);
btn.DrawToBitmap(bmp, new Rectangle(0, 0, btn.Width, btn.Height));
PictureBox pb = new PictureBox();
pb.Size = btn.Size;
pb.Image = bmp;
要在另一个控件的Paint事件中使用此方法,您将从控件中创建Bitmap,如上所示,然后在控件的表面上绘制它,如下所示:
e.Graphics.DrawImage(bmp, 0, 0);
bmp.Dispose();
也许你所追求的是一个“面板”,你可以继承,然后创建自己的行为?
class MyPanel : System.Windows.Forms.Panel
{
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint(e);
}
}
抓住e.graphics,你可以在控件的范围内做任何你想做的事情。 从内存中你可以设置控件等的最小大小,但是你需要跳转到MSDN中的windows.forms文档以获取更多细节(或者你可以在这里提出另一个问题;))。
或者,如果您的实例添加功能,您应该从控件继承您尝试增强和覆盖它的paint方法?
也许你可以详细说明(在你的问题中)你想做什么?
public delegate void OnPaintDelegate( PaintEventArgs e );
private void panel1_Paint( object sender, PaintEventArgs e ) {
OnPaintDelegate paintDelegate = (OnPaintDelegate)Delegate.CreateDelegate(
typeof( OnPaintDelegate )
, this.button1
, "OnPaint" );
paintDelegate( e );
}
你可以添加/覆盖OnPaint处理程序@TcKs建议或使用BitBlt函数:
[DllImport("gdi32.dll")]
private static extern bool BitBlt(
IntPtr hdcDest,
int nXDest,
int nYDest,
int nWidth,
int nHeight,
IntPtr hdcSrc,
int nXSrc,
int nYSrc,
int dwRop
);
private const Int32 SRCCOPY = 0xCC0020;
....
Graphics sourceGraphics = sourceControl.CreateGraphics();
Graphics targetGraphics = targetControl.CreateGraphics();
Size controlSize = sourceControl.Size;
IntPtr sourceDc = sourceGraphics.GetHdc();
IntPtr targerDc = targetGraphics.GetHdc();
BitBlt(targerDc, 0, 0, controlSize.Width, controlSize.Height, sourceDc, 0, 0, SRCCOPY);
sourceGraphics.ReleaseHdc(sourceDc);
targetGraphics.ReleaseHdc(targerDc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.