簡體   English   中英

有沒有辦法在C#中對其他控件進行控制?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM