繁体   English   中英

如何在C#winforms中将背景图像放置到DateTimePicker?

[英]How to put a background image to DateTimePicker in C# winforms?

我正在尝试创建一些用户控件。

并且还尝试通知必须选择控件或使用用户输入编写控件。

因此,我的想法是在控件的右上角绘制图像。

我已经成功完成了TextBox控件。

在此处输入图片说明

但是对于DateTimePicker控件,我不知道从哪里开始。

这是我的代码如下:

public partial class DateTimePicker : System.Windows.Forms.DateTimePicker
{
    public DateTimePicker()
    {
        InitializeComponent();

    }

    protected override void OnLayout(LayoutEventArgs levent)
    {
        base.OnLayout(levent);


        Bitmap bmp  = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("MyControls.Resources.Images.required01.gif"));
        this.Parent.CreateGraphics().DrawImage(bmp, 10, 10);
    }
}

this.Parent.CreateGraphics()不会在表单上绘制任何图像。

约书亚

对于自定义绘画,DateTimePicker控件具有一些限制,因此您可能必须深入了解并覆盖控件的“窗口过程”。

下面的实现使用“关闭标签”方式,该方式使用WM_PAINT消息在默认绘制完成后在控件上进行绘制。 请注意,在处理WM_PAINT消息时,我们通常不调用GetDC()或其等效的Graphics.FromHwnd(),但是在这种情况下,我们不想覆盖原始绘画的任何部分。 我们只想在完成基本过程的处理后绘制位图。

public partial class UserControl1 : System.Windows.Forms.DateTimePicker
{
    private Bitmap bmp = null;
    public UserControl1()
    {
        InitializeComponent();
        bmp = new Bitmap(5, 5);
        bmp.SetPixel(2, 2, Color.Red); //Placeholder, Load the bitmap here
    }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == 0xf) //WM_PAINT message
        {
            Graphics g = Graphics.FromHwnd(m.HWnd);
            g.DrawImage(bmp, ClientRectangle.Width - 8, 3);
            g.Dispose();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM