Изменить положение названия формы

189
25 сентября 2018, 23:50

В примере название формы находится по центру

Но у себя почему-то не могу изменить положение текста, в свойствах формы просто не вижу такого пункта. Какое свойство отвечает за это?

Answer 1

Вот такой можно сделать костыль (накидать пробелов перед тайтлом)! :D Минус очевиден - работает только для фиксированного размера формы, для растягиваемой - нужно при ресайзе постоянно пересчитывать.

private void CenterTitle()
{
    //упоротый TextRenderer коряво считает ширину короткого текста, 
    //возможно нужна другая перегрузка
    var titleWidth = TextRenderer.MeasureText(Text + Text, Font).Width / 2.0;
    var fillerRequiredWidth = (this.Width - titleWidth) / 2;
    //упоротый TextRenderer коряво считает ширину короткого текста, 
    //возможно нужна другая перегрузка
    var spaceWidth = TextRenderer.MeasureText("                    ", Font).Width / 20.0;
    var spaceCount = (int)Math.Ceiling(fillerRequiredWidth / spaceWidth);
    var spaces = new String(' ', spaceCount);
    Text = spaces + Text;
}
Answer 2

Вид строки заголовка и рамки у окна полностью определяется Windows. Если вы хотите его изменить, нужно реализовать их отображение самостоятельно. Это можно сделать, например, обработкой сообщения WM_NCPAINT, как здесь. Но можно попробовать и вот так:

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

namespace WindowsFormsTest
{
    public partial class Form1 : Form
    {
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;
        private const int HTLEFT = 10, HTRIGHT = 11, HTTOP = 12,  HTTOPLEFT = 13,
        HTTOPRIGHT = 14, HTBOTTOM = 15, HTBOTTOMLEFT = 16, HTBOTTOMRIGHT = 17;
        const int sizew = 5;
        const int htitle = 26;
        Rectangle TopRc { get { return new Rectangle(0, 0, this.ClientSize.Width, sizew); } }
        Rectangle LeftRc { get { return new Rectangle(0, 0, sizew, this.ClientSize.Height); } }
        Rectangle BottomRc { get { return new Rectangle(0, this.ClientSize.Height - sizew, this.ClientSize.Width, sizew); } }
        Rectangle RightRc { get { return new Rectangle(this.ClientSize.Width - sizew, 0, sizew, this.ClientSize.Height); } }
        Rectangle TopLeft { get { return new Rectangle(0, 0, sizew, sizew); } }
        Rectangle TopRight { get { return new Rectangle(this.ClientSize.Width - sizew, 0, sizew, sizew); } }
        Rectangle BottomLeft { get { return new Rectangle(0, this.ClientSize.Height - sizew, sizew, sizew); } }
        Rectangle BottomRight { get { return new Rectangle(this.ClientSize.Width - sizew, this.ClientSize.Height - sizew, sizew, sizew); } }

        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        public Form1()
        {
            InitializeComponent();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;            
            this.DoubleBuffered = true;
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            Label labelTitle = new Label();
            labelTitle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));            
            labelTitle.Location = new System.Drawing.Point(sizew + htitle, sizew);
            labelTitle.Name = "labelTitle";
            labelTitle.Size = new System.Drawing.Size(this.Width - htitle * 2 - sizew - 6, htitle);            
            labelTitle.Text = this.Text;
            labelTitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            labelTitle.MouseDown += new System.Windows.Forms.MouseEventHandler(this.label1_MouseDown);
            this.Controls.Add(labelTitle);
            Button bClose = new Button();
            bClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            bClose.Location = new System.Drawing.Point(this.Width - htitle - sizew, sizew);
            bClose.Name = "bClose";
            bClose.Size = new System.Drawing.Size(htitle, htitle);            
            bClose.Text = "X";
            bClose.UseVisualStyleBackColor = true;
            bClose.Click += new System.EventHandler(this.button2_Click);
            this.Controls.Add(bClose);
            Icon icon = this.Icon;
            Bitmap bmp = icon.ToBitmap();
            PictureBox pbox = new PictureBox();
            pbox.Location = new Point(sizew, sizew);
            pbox.Image = bmp;
            pbox.SizeMode = PictureBoxSizeMode.Zoom;
            pbox.Size = new Size(htitle, htitle);
            this.Controls.Add(pbox);
        }

        protected override void OnPaint(PaintEventArgs e) 
        {
            e.Graphics.FillRectangle(Brushes.Gray, TopRc);
            e.Graphics.FillRectangle(Brushes.Gray, LeftRc);
            e.Graphics.FillRectangle(Brushes.Gray, RightRc);
            e.Graphics.FillRectangle(Brushes.Gray, BottomRc);
        }

        protected override void WndProc(ref Message message)
        {
            base.WndProc(ref message);
            if (message.Msg == 0x84) // WM_NCHITTEST
            {
                var cursor = this.PointToClient(Cursor.Position);
                if (TopLeft.Contains(cursor)) message.Result = (IntPtr)HTTOPLEFT;
                else if (TopRight.Contains(cursor)) message.Result = (IntPtr)HTTOPRIGHT;
                else if (BottomLeft.Contains(cursor)) message.Result = (IntPtr)HTBOTTOMLEFT;
                else if (BottomRight.Contains(cursor)) message.Result = (IntPtr)HTBOTTOMRIGHT;
                else if (TopRc.Contains(cursor)) message.Result = (IntPtr)HTTOP;
                else if (LeftRc.Contains(cursor)) message.Result = (IntPtr)HTLEFT;
                else if (RightRc.Contains(cursor)) message.Result = (IntPtr)HTRIGHT;
                else if (BottomRc.Contains(cursor)) message.Result = (IntPtr)HTBOTTOM;
            }
        }

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

Источники:

Move window/form without Titlebar in C# - CodeProject

How to move and resize a form without a border

READ ALSO
Представить строку в xml формате

Представить строку в xml формате

Из БД достаю информацию типа byte[], преобразовываю в stringВ результате получаю длинную строку с xml данными:

149
C# Post request

C# Post request

Необходимо отправить POST запросом XML файлПри получении ответа получаю ошибку java

194
Вывод данных из MySQL по категориям

Вывод данных из MySQL по категориям

Есть база данных, в ней 2 таблицы(category_sklad состоящая из id name и products_sklad состоящая из id name kolvo category_id)Собственно вот что планируется сделать, например...

185
Что означает запись в error log?

Что означает запись в error log?

Всем привет! Отлавливаю ошибку wordpress + ubuntu 1604 , apache2

166