简体   繁体   English

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

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

I am trying to create some user controls. 我正在尝试创建一些用户控件。

And also trying to notify that the control must be selected or written with user input. 并且还尝试通知必须选择控件或使用用户输入编写控件。

So, my idea is to draw image on the right-top corner of the control. 因此,我的想法是在控件的右上角绘制图像。

I have successfully done with TextBox control. 我已经成功完成了TextBox控件。

在此处输入图片说明

But for the DateTimePicker control, I have no idea where to start with. 但是对于DateTimePicker控件,我不知道从哪里开始。

Here is my code below: 这是我的代码如下:

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() does not draw any image on the form. this.Parent.CreateGraphics()不会在表单上绘制任何图像。

Joshua, 约书亚

The DateTimePicker control has some restrictions when it comes to custom painting, so you will probably have to go under the hood and override the Window Procedure of the control. 对于自定义绘画,DateTimePicker控件具有一些限制,因此您可能必须深入了解并覆盖控件的“窗口过程”。

The following implementation uses an "off label" way of using the WM_PAINT message to draw on the control after the default painting has been done. 下面的实现使用“关闭标签”方式,该方式使用WM_PAINT消息在默认绘制完成后在控件上进行绘制。 Note that we usually don't call GetDC() or its equivalent Graphics.FromHwnd() when processing the WM_PAINT message, but in this case we don't want to override any part of the original painting. 请注意,在处理WM_PAINT消息时,我们通常不调用GetDC()或其等效的Graphics.FromHwnd(),但是在这种情况下,我们不想覆盖原始绘画的任何部分。 We merely want to draw our bitmap after it finishes its processing by the base procedure. 我们只想在完成基本过程的处理后绘制位图。

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