Модераторы: Partizan, gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Как создать свой класс формы? 
V
    Опции темы
Elfet
  Дата 10.8.2007, 13:52 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Белый и Пушистый
****


Профиль
Группа: Awaiting Authorisation
Сообщений: 3776
Регистрация: 2.4.2003

Репутация: нет
Всего: 16



Как создать свой класс формы с переопределённым методом рисования (что бы самому рисовать форму) от которого можно создовать уже свои формы?
Заранее спасибо! 

PS У меня не получилось:
MyForm
Код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace MyForm
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
            buttons = new List<Button>();
        }

        #region Images
        private Image leftTopBorder;
        protected Image LeftTopBorder
        {
            get
            {
                return leftTopBorder;
            }
            set
            {
                leftTopBorder = value;
            }
        }
        private Image rightTopBorder;
        protected Image RightTopBorder
        {
            get
            {
                return rightTopBorder;
            }
            set
            {
                rightTopBorder = value;
            }
        }
        private Image leftBottomBorder;
        protected Image LeftBottomBorder
        {
            get
            {
                return leftBottomBorder;
            }
            set
            {
                leftBottomBorder = value;
            }
        }
        private Image rightBottomBorder;
        protected Image RightBottomBorder
        {
            get
            {
                return rightBottomBorder;
            }
            set
            {
                rightBottomBorder = value;
            }
        }
        private Image topBorder;
        protected Image TopBorder
        {
            get
            {
                return topBorder;
            }
            set
            {
                topBorder = value;
            }
        }

        private Image bottomBorder;
        protected Image BottomBorder
        {
            get
            {
                return bottomBorder;
            }
            set
            {
                bottomBorder = value;
            }
        }

        private Image leftBorder;
        protected Image LeftBorder
        {
            get
            {
                return leftBorder;
            }
            set
            {
                leftBorder = value;
            }
        }

        private Image rightBorder;
        protected Image RightBorder
        {
            get
            {
                return rightBorder;
            }
            set
            {
                rightBorder = value;
            }
        }
        #endregion

        private int captionSize = 0;
        public int CaptionSize
        {
            get
            {
                return captionSize;
            }
            set
            {
                captionSize = value;
            }
        }

        protected void MyForm_Paint(object sender, PaintEventArgs e)
        {
            if (leftBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(leftBorder, WrapMode.TileFlipX), 0f, 0f, leftBorder.Width, Height);
            if (rightBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(rightBorder, WrapMode.TileFlipX), 0f, Height - rightBorder.Height, leftBorder.Width, Height);
            if (topBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(topBorder, WrapMode.TileFlipX), 0f, 0f, Width, topBorder.Height);
            if (bottomBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(bottomBorder, WrapMode.TileFlipX), Width - bottomBorder.Width, 0f, Width, bottomBorder.Height);
            
            if (leftTopBorder != null)
                e.Graphics.DrawImage(leftTopBorder, 0, 0);
            if (rightTopBorder != null)
                e.Graphics.DrawImage(rightTopBorder, Width - rightTopBorder.Width, 0);
            if (leftBottomBorder != null)
                e.Graphics.DrawImage(leftBottomBorder, 0, Height - leftBottomBorder.Height);
            if (rightBottomBorder != null)
                e.Graphics.DrawImage(rightBottomBorder, Width - rightBottomBorder.Width, Height - rightBottomBorder.Height);

            foreach (Button button in buttons)
            {
                if (button.Visable)
                {
                    e.Graphics.DrawImage(button.Image, button.DrawPoint);
                }
            }
        }

        private List<Button> buttons;
        protected void AddButton(Button button)
        {
            buttons.Add(button);
        }

        #region Пещение и Ресайз
        protected override void WndProc(ref Message m)
        {
            const int WM_NCHITTEST = 0x0084;
            const int HTTOP = 12;
            const int HTTOPLEFT = 13;
            const int HTTOPRIGHT = 14;
            const int HTBOTTOMLEFT = 16;
            const int HTBOTTOMRIGHT = 17;
            const int HTLEFT = 10;
            const int HTRIGHT = 11;
            const int HTBOTTOM = 15;

            const int HTCAPTION = 0x0002;
            const int MOUSEAWARE_BORDERWIDTH = 5;
            // Default behaviour
            base.WndProc(ref m);

            // Trap the message sent when the mouse is over the borders
            if (m.Msg == WM_NCHITTEST)
            {
                int pos = m.LParam.ToInt32();
                short yPos = (short)(pos >> 16);
                short xPos = (short)pos;
                Point pt = this.PointToClient(new Point(xPos, yPos));
                if (pt.X < MOUSEAWARE_BORDERWIDTH && pt.Y < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTTOPLEFT);
                }
                else if (pt.Y < MOUSEAWARE_BORDERWIDTH && pt.X > Width - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTTOPRIGHT);
                }
                else if (pt.Y > Height - MOUSEAWARE_BORDERWIDTH && pt.X < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTBOTTOMLEFT);
                }
                else if (pt.Y > Height - MOUSEAWARE_BORDERWIDTH && pt.X > Width - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTBOTTOMRIGHT);
                }
                else if (pt.Y > Height - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTBOTTOM);
                }
                else if (pt.Y < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTTOP);
                }
                else if (pt.X > Width - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTRIGHT);
                }
                else if (pt.X < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTLEFT);
                }
                else if (pt.Y < captionSize || pt.Y > Height - captionSize)
                {
                    // А тут обходим со всемх сторон наши кнопочки :) 
                    bool caption = true;
                    foreach (Button but in buttons)
                    {
                        if (but.Visable && but.Active.Contains(pt.X, pt.Y))
                        {
                            caption = false;
                        }
                    }
                    if (caption)
                        m.Result = new IntPtr(HTCAPTION);
                }
            }
        }
        #endregion

        private void MyForm_Resize(object sender, EventArgs e)
        {
            Invalidate();
        }

    }
}


Form1
Код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TestMyForm
{
    public partial class Form1 : MyForm.MyForm
    {
        public Form1()
        {
            CaptionSize = 20;
            TopBorder = Properties.Resources.top;
            LeftTopBorder = Properties.Resources.topleft;
            RightBorder = Properties.Resources.topright;
            LeftBottomBorder = Properties.Resources.bottomleft;
            RightBottomBorder = Properties.Resources.bottomright;
            InitializeComponent();
            Invalidate();
            /*AddButton(new MyForm.Button(
                gf,
                Hide,
                MyForm.HorizontalAlignment.Right,
                MyForm.VerticalAlignment.Top,
                new PointF(10, 10),
                true,
                this.Size
                ));*/
        }
    }
}



--------------------
PM MAIL WWW Skype   Вверх
Idsa
Дата 10.8.2007, 14:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник
Сообщений: 2086
Регистрация: 5.12.2006
Где: Томск

Репутация: 14
Всего: 62



Цитата(Elfet @  10.8.2007,  13:52 Найти цитируемый пост)
Как создать свой класс формы с переопределённым методом рисования (что бы самому рисовать форму) от которого можно создовать уже свои формы?

Просто перегружаем OnPaint:
Код

protected override void OnPaint(PaintEventArgs e)
{
   base.OnPaint(e);
   ...
}



--------------------
Мой блог: alexidsa.blogspot.com
PM MAIL ICQ   Вверх
Elfet
Дата 10.8.2007, 15:34 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Белый и Пушистый
****


Профиль
Группа: Awaiting Authorisation
Сообщений: 3776
Регистрация: 2.4.2003

Репутация: нет
Всего: 16



Вот, так вот написал, но всё равно почему то не выходит :/
Код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace MyForm
{
    public class MyForm : Form
    {
        public MyForm()
        {
            this.FormBorderStyle = FormBorderStyle.None;
        }

        #region Images
        private Image leftTopBorder;
        protected Image LeftTopBorder
        {
            get
            {
                return leftTopBorder;
            }
            set
            {
                leftTopBorder = value;
            }
        }
        private Image rightTopBorder;
        protected Image RightTopBorder
        {
            get
            {
                return rightTopBorder;
            }
            set
            {
                rightTopBorder = value;
            }
        }
        private Image leftBottomBorder;
        protected Image LeftBottomBorder
        {
            get
            {
                return leftBottomBorder;
            }
            set
            {
                leftBottomBorder = value;
            }
        }
        private Image rightBottomBorder;
        protected Image RightBottomBorder
        {
            get
            {
                return rightBottomBorder;
            }
            set
            {
                rightBottomBorder = value;
            }
        }
        private Image topBorder;
        protected Image TopBorder
        {
            get
            {
                return topBorder;
            }
            set
            {
                topBorder = value;
            }
        }

        private Image bottomBorder;
        protected Image BottomBorder
        {
            get
            {
                return bottomBorder;
            }
            set
            {
                bottomBorder = value;
            }
        }

        private Image leftBorder;
        protected Image LeftBorder
        {
            get
            {
                return leftBorder;
            }
            set
            {
                leftBorder = value;
            }
        }

        private Image rightBorder;
        protected Image RightBorder
        {
            get
            {
                return rightBorder;
            }
            set
            {
                rightBorder = value;
            }
        }
        #endregion

        private int captionSize = 0;
        protected int CaptionSize
        {
            get
            {
                return captionSize;
            }
            set
            {
                captionSize = value;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (leftBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(leftBorder, WrapMode.TileFlipX), 0f, 0f, leftBorder.Width, Height);
            if (rightBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(rightBorder, WrapMode.TileFlipX), 0f, Height - rightBorder.Height, leftBorder.Width, Height);
            if (topBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(topBorder, WrapMode.TileFlipX), 0f, 0f, Width, topBorder.Height);
            if (bottomBorder != null)
                e.Graphics.FillRectangle(new TextureBrush(bottomBorder, WrapMode.TileFlipX), Width - bottomBorder.Width, 0f, Width, bottomBorder.Height);
            
            if (leftTopBorder != null)
                e.Graphics.DrawImage(leftTopBorder, 0, 0);
            if (rightTopBorder != null)
                e.Graphics.DrawImage(rightTopBorder, Width - rightTopBorder.Width, 0);
            if (leftBottomBorder != null)
                e.Graphics.DrawImage(leftBottomBorder, 0, Height - leftBottomBorder.Height);
            if (rightBottomBorder != null)
                e.Graphics.DrawImage(rightBottomBorder, Width - rightBottomBorder.Width, Height - rightBottomBorder.Height);
        }

        #region Пещение и Ресайз
        protected override void WndProc(ref Message m)
        {
            const int WM_NCHITTEST = 0x0084;
            const int HTTOP = 12;
            const int HTTOPLEFT = 13;
            const int HTTOPRIGHT = 14;
            const int HTBOTTOMLEFT = 16;
            const int HTBOTTOMRIGHT = 17;
            const int HTLEFT = 10;
            const int HTRIGHT = 11;
            const int HTBOTTOM = 15;

            const int HTCAPTION = 0x0002;
            const int MOUSEAWARE_BORDERWIDTH = 5;
            // Default behaviour
            base.WndProc(ref m);

            // Trap the message sent when the mouse is over the borders
            if (m.Msg == WM_NCHITTEST)
            {
                int pos = m.LParam.ToInt32();
                short yPos = (short)(pos >> 16);
                short xPos = (short)pos;
                Point pt = this.PointToClient(new Point(xPos, yPos));
                if (pt.X < MOUSEAWARE_BORDERWIDTH && pt.Y < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTTOPLEFT);
                }
                else if (pt.Y < MOUSEAWARE_BORDERWIDTH && pt.X > Width - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTTOPRIGHT);
                }
                else if (pt.Y > Height - MOUSEAWARE_BORDERWIDTH && pt.X < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTBOTTOMLEFT);
                }
                else if (pt.Y > Height - MOUSEAWARE_BORDERWIDTH && pt.X > Width - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTBOTTOMRIGHT);
                }
                else if (pt.Y > Height - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTBOTTOM);
                }
                else if (pt.Y < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTTOP);
                }
                else if (pt.X > Width - MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTRIGHT);
                }
                else if (pt.X < MOUSEAWARE_BORDERWIDTH)
                {
                    m.Result = new IntPtr(HTLEFT);
                }
                else if (pt.Y < captionSize || pt.Y > Height - captionSize)
                {
                    m.Result = new IntPtr(HTCAPTION);
                }
            }
        }
        #endregion
    }
}



Код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TestMyForm
{
    public partial class Form1 : MyForm.MyForm
    {
        public Form1()
            : base()
        {
            InitializeComponent();
            CaptionSize = 20;
            TopBorder = Properties.Resources.top;
            LeftTopBorder = Properties.Resources.topleft;
            RightBorder = Properties.Resources.topright;
            LeftBottomBorder = Properties.Resources.bottomleft;
            RightBottomBorder = Properties.Resources.bottomright;
            Invalidate();
        }
    }
}


Создаётся форма MyForm, а не Form1. Те параметры что я указал в Form1 не действуют. А действуют только из MyForm


--------------------
PM MAIL WWW Skype   Вверх
Idsa
Дата 10.8.2007, 15:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Участник
Сообщений: 2086
Регистрация: 5.12.2006
Где: Томск

Репутация: 14
Всего: 62



Цитата(Elfet @  10.8.2007,  15:34 Найти цитируемый пост)
Создаётся форма MyForm, а не Form1. Те параметры что я указал в Form1 не действуют. А действуют только из MyForm 

Загляни в Program.cs и исправь "new MyForm()" на "new Form1()".


--------------------
Мой блог: alexidsa.blogspot.com
PM MAIL ICQ   Вверх
Elfet
Дата 10.8.2007, 15:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Белый и Пушистый
****


Профиль
Группа: Awaiting Authorisation
Сообщений: 3776
Регистрация: 2.4.2003

Репутация: нет
Всего: 16



smile
Код

            Application.Run(new Form1());


Добавлено через 13 секунд
Всё равно :/

Добавлено через 7 минут и 59 секунд
О! Заработало! smile Тока я не понял почему :( Я в первый раз как-то это пытался два проекто объеденить smile Спасибо!


--------------------
PM MAIL WWW Skype   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
mr.DUDA
THandle

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.
Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)? Пишите сюда, или отправляйте репорт. Поставим :)
Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, THandle.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Общие вопросы по .NET и C# | Следующая тема »


 




[ Время генерации скрипта: 0.0500 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.