Фон DateTime
От: adontz Грузия http://adontz.wordpress.com/
Дата: 19.04.06 00:54
Оценка:
Как установить цвет показанный как жёлтый? Состояние выпадающего Month не принципиально.
A journey of a thousand miles must begin with a single step © Lau Tsu
Re: Фон DateTime
От: ekamaloff Великобритания  
Дата: 19.04.06 06:06
Оценка: 12 (1)
Здравствуйте, adontz, Вы писали:

A>Как установить цвет показанный как жёлтый? Состояние выпадающего Month не принципиально.


Не знаю как в .NET, а в WinAPI по шагам это можно сделать так:


Проверено в Delphi — работает.

Вот код на всякий случай, не думаю, что тут сам язык какое-то значение имеет:

// ...
type
  TForm1 = class(TForm)
    DateTimePicker1: TDateTimePicker;
    procedure FormCreate(Sender: TObject);
  private
    m_Brush: HBRUSH;
    m_OldDTPWndProc: TWndMethod;
    procedure DTPWndProc(var Message: TMessage);
    // ...
  end;

implementation

// ...

procedure TForm1.FormCreate(Sender: TObject);
begin
    m_Brush := CreateSolidBrush(RGB(255, 255, 0));
    m_OldDTPWndProc := DateTimePicker1.WindowProc;
    DateTimePicker1.WindowProc := DTPWndProc;
end;

procedure TForm1.DTPWndProc(var Message: TMessage);
var
    ps: TPaintStruct;
    dc: HDC;
    oldbr: HBRUSH;
begin
    case Message.Msg of
      WM_PAINT: begin
        dc := BeginPaint(DateTimePicker1.Handle, ps);
        FillRect(dc, DateTimePicker1.ClientRect, m_Brush);
        EndPaint(DateTimePicker1.Handle, ps);
        InvalidateRect(DateTimePicker1.Handle, nil, False);
      end;
    end;
    m_OldDTPWndProc(Message);
end;
It is always bad to give advices, but you will be never forgiven for a good one.
Oscar Wilde
Re: Фон DateTime
От: Indifferent Украина  
Дата: 19.04.06 06:23
Оценка: 12 (1)
Здравствуйте, adontz, Вы писали:

A>Как установить цвет показанный как жёлтый? Состояние выпадающего Month не принципиально.

A>

идея здесь
using System;
using System.Windows.Forms;
using System.Drawing;
class Demo
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }

    public class MainForm : Form
    {
        private DateTimePicker2 dtp;

        public MainForm()
        {
            this.Name = "MainForm";
            this.Text = "Demo";
               this.Size = new Size(400, 350);


            dtp = new DateTimePicker2();
            dtp.Location = new Point(12,12);
            //скрытое свойство
            dtp.BackColor = Color.Yellow;

            this.Controls.Add(this.dtp);

        }

    }


    internal class DateTimePicker2 : DateTimePicker
    {
        public DateTimePicker2()
        {
        }

        protected override void WndProc(ref Message m)
        {
            //     Check to see if message being send is WM_ERASEBKGND.
            //     The hex value of this message is hex 14.
            //     This message is sent when the background of the
            //     object needs to be erased. In our case though, instead of
            //     erasing it, we will paint a rectangle over it
            if(m.Msg == 0x14 && Enabled) // Then ' WM_ERASEBKGND
            {
                using(Graphics g = Graphics.FromHdc(m.WParam))
                {
                    g.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
                }
                return;
            }
            base.WndProc(ref m);
        }
    }

}
... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
Re[2]: Фон DateTime
От: adontz Грузия http://adontz.wordpress.com/
Дата: 19.04.06 11:08
Оценка:
Здравствуйте, ekamaloff, Вы писали:

E>
  • В его новой оконной процедуре перехват сообщения WM_PAINT, в нем:
    E>
  • BeginPaint
    E>
  • Заливка клиентской области желтой кистью
    E>
  • EndPaint
    E>
  • Инвалидировать заново всю клиентскую область — InvalidateRect
    E>
  • Вызвать старую оконную процедуру

    А почему не Erase Background?
  • A journey of a thousand miles must begin with a single step © Lau Tsu
    Re[2]: Фон DateTime
    От: adontz Грузия http://adontz.wordpress.com/
    Дата: 19.04.06 14:45
    Оценка:
    Здравствуйте, Indifferent, Вы писали:

    Мне новый DateTime не подходит. Мне надо у уже существующих. но если другого пути нет...
    A journey of a thousand miles must begin with a single step © Lau Tsu
    Re[3]: Фон DateTime
    От: Indifferent Украина  
    Дата: 20.04.06 06:55
    Оценка: 44 (2)
    Здравствуйте, adontz, Вы писали:

    A>Здравствуйте, Indifferent, Вы писали:


    A>Мне новый DateTime не подходит. Мне надо у уже существующих. но если другого пути нет...

    ... в руках у нас ...

    Почему не подходит?

    Решения есть, см. в:
    Как можно перехватить Windows сообщения (WM_X), посылаемые в оконную процедуру control'a?


    ниже вариант реализации механизма Subclassing'a

    механизм Subclassing'a, при котором подменяется оконная процедура и следовательно все сообщения сначала приходят в новую процедуру, а затем (по усмотрению) уже в оригинальную. В .NET такая функциональность обеспечивается при помощи наследования от класса System.Windows.Forms.NativeWindow


    using System;
    using System.Windows.Forms;
    using System.Drawing;
    class Demo
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());
            }
        }
    
        public class MainForm : Form
        {
            private DateTimePicker dtp1;
    
            public MainForm()
            {
                this.Name = "MainForm";
                this.Text = "Demo";
                   this.Size = new Size(400, 350);
    
    
                dtp1 = new DateTimePicker();
                dtp1.Location = new Point(12,12);
                dtp1.BackColor = Color.Aqua;
                this.Controls.Add(this.dtp1);
    
                dtpNativeWindow myNativeWindow = new dtpNativeWindow(dtp1);
    
            }
    
        }
    
    
        class dtpNativeWindow : NativeWindow
        {
            private Control _control = null;
            public dtpNativeWindow(Control control)
            {
                _control = control;
                control.HandleCreated += new EventHandler(OnHandleCreated);
                control.HandleDestroyed += new EventHandler(OnHandleDestroyed);
            }
            void OnHandleCreated(object sender, EventArgs e)
            {
                AssignHandle(((Control)sender).Handle);
            }
            void OnHandleDestroyed(object sender, EventArgs e)
            {
                ReleaseHandle();
            }
            const int WM_ERASEBKGND = 0x14;
            protected override void WndProc(ref Message m)
            {
                if(m.Msg == WM_ERASEBKGND && _control.Enabled)
                {
                    using(Graphics g = Graphics.FromHdc(m.WParam))
                    {
                        g.FillRectangle(new SolidBrush(_control.BackColor), _control.ClientRectangle);
                    }
                    return;
                }
                base.WndProc(ref m);
            }
        }
    
    
    }
    ... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
    Re[4]: Фон DateTime
    От: adontz Грузия http://adontz.wordpress.com/
    Дата: 20.04.06 11:42
    Оценка:
    Здравствуйте, Indifferent, Вы писали:

    I>Решения есть, см. в:

    I>Как можно перехватить Windows сообщения (WM_X), посылаемые в оконную процедуру control'a?

    О! Как всё оригинально!
    Спасибо!
    A journey of a thousand miles must begin with a single step © Lau Tsu
    Re[4]: Фон DateTime
    От: Аноним  
    Дата: 14.08.06 10:06
    Оценка:
    Не работает данное решение в NET 2.0
    Yes, DavKos


    данное сообщение получено с www.gotdotnet.ru
    ссылка на оригинальное сообщение
    Фон DateTimePicker
    От: adontz Грузия http://adontz.wordpress.com/
    Дата: 14.08.06 10:23
    Оценка: 1 (1)
    #Имя: FAQ.dotnet.gui.DateTimePicker.BackColor
    Здравствуйте, davkos, Вы писали:

    A>Как установить цвет показанный как жёлтый? Состояние выпадающего Month не принципиально.



    D> Не работает данное решение в NET 2.0


    Почему не работает? У меня всё работает. Вот код.

            private class BackColorWorkaroundSubclass : NativeWindow
            {
                private const int WM_ERASEBKGND = 0x0014;
    
                private Control _control;
                private SolidBrush _brush;
    
                private void OnHandleDestroyed(object sender, EventArgs e)
                {
                    Detach();
                }
    
                public BackColorWorkaroundSubclass(Control control)
                {
                    Attach(control);
                }
    
                public void Attach(Control control)
                {
                    this._control = control;
                    this._brush = new SolidBrush(this._control.BackColor);
                    AssignHandle(this._control.Handle);
                    this._control.HandleDestroyed += new EventHandler(OnHandleDestroyed);
                }
    
                public void Detach()
                {
                    ReleaseHandle();
                    this._brush = null;
                }
    
                protected override void WndProc(ref Message message)
                {
                    if (message.Msg == WM_ERASEBKGND)
                    {
                        using (Graphics graphics = Graphics.FromHdc(message.WParam))
                        {
                            graphics.FillRectangle(this._brush, this._control.ClientRectangle);
                        }
                    }
                    else
                    {
                        base.WndProc(ref message);
                    }
                }
            }
    A journey of a thousand miles must begin with a single step © Lau Tsu
    Re[5]: Фон DateTime
    От: Аноним  
    Дата: 14.08.06 11:13
    Оценка:
                dtp1 = new DateTimePicker();
                dtp1.Location = new Point(12,12);
                dtp1.BackColor = Color.Aqua;

    У DateTimePicker в NET 2.0 свойства BackColor нет!
    Yes, DavKos


    данное сообщение получено с www.gotdotnet.ru
    ссылка на оригинальное сообщение
    Re[6]: Фон DateTime
    От: adontz Грузия http://adontz.wordpress.com/
    Дата: 14.08.06 11:35
    Оценка:
    Здравствуйте, davkos, Вы писали:

    D>У DateTimePicker в NET 2.0 свойства BackColor нет!


    Ага, щас Куда ему деться то?
    A journey of a thousand miles must begin with a single step © Lau Tsu
    Re[6]: Фон DateTime
    От: Аноним  
    Дата: 15.08.06 06:40
    Оценка:
    Дак вот нет....
    Смотрю внимательно System.Windows.Forms.DateTimePicker

    Setting the BackColor has no effect on the appearance of the DateTimePicker. To set the background color for the drop-down calendar of the DateTimePicker, see the CalendarMonthBackground property.

    В PropertyGrid его нет вообще, видимо отфильтрован...
    Yes, DavKos


    данное сообщение получено с www.gotdotnet.ru
    ссылка на оригинальное сообщение
    Re[6]: Фон DateTime
    От: _FRED_ Черногория
    Дата: 15.08.06 06:59
    Оценка:
    Здравствуйте, adontz, Вы писали:

    A>Почему не работает? У меня всё работает. Вот код.

    A>        private class BackColorWorkaroundSubclass : NativeWindow
    A>        {
                …
    A>            private void OnHandleDestroyed(object sender, EventArgs e)
    A>            {
    A>                Detach();
    A>            }
    
    A>            public BackColorWorkaroundSubclass(Control control)
    A>            {
    A>                Attach(control);
    A>            }
    
    A>            public void Attach(Control control)
    A>            {
    A>                this._control = control;
    A>                this._brush = new SolidBrush(this._control.BackColor);
    A>                AssignHandle(this._control.Handle);
    A>                this._control.HandleDestroyed += new EventHandler(OnHandleDestroyed);
    A>            }
    
    A>            public void Detach()
    A>            {
    A>                ReleaseHandle();
    A>                this._brush = null;
    A>            }
                …
    A>        }

    Только надо быть внимательным:

    NET Framework Class Library

    Control.HandleDestroyed Event

    Occurs when the control's handle is in the process of being destroyed.

    Remarks
    During the HandleDestroyed event, the control is still a valid Windows control and the Handle can be recreated by calling the RecreateHandle method.


    То есть неплохо бы ловить и HandleCreated
    ... << RSDN@Home 1.2.0 alpha rev. 652>>
    Now playing: «Тихо в лесу…»
    Help will always be given at Hogwarts to those who ask for it.
    Re[7]: Фон DateTime
    От: adontz Грузия http://adontz.wordpress.com/
    Дата: 15.08.06 07:50
    Оценка:
    Здравствуйте, davkos, Вы писали:

    D>Смотрю внимательно System.Windows.Forms.DateTimePicker

    D>Setting the BackColor has no effect on the appearance of the DateTimePicker. To set the background color for the drop-down calendar of the DateTimePicker, see the CalendarMonthBackground property.
    D>В PropertyGrid его нет вообще, видимо отфильтрован...


    Так потому и писался Workaround чтобы самим сделать это свойство осмысленным.
    A journey of a thousand miles must begin with a single step © Lau Tsu
     
    Подождите ...
    Wait...
    Пока на собственное сообщение не было ответов, его можно удалить.