2

В примере название формы находится по центру Должно быть так

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

Сейчас так

4
  • 1
    Рискну предположить, что это никак не изменить, ибо оформление окон управляется виндами. Для кастомных заголовков потребуется безрамочное окно и чуть-чуть творчества. Например.
    – free_ze
    25 июл 2018 в 11:34
  • 1
    +1 к тому, что разница обусловлена используемой версией Windows (8/10 в примере, 7 у Вас) и изменить положение просто так не получится. Но если хочется не просто, то посмотрите похожий вопрос на английском: stackoverflow.com/questions/11947314/… 25 июл 2018 в 11:51
  • 1
    Суждение не верно о версии виндовс - пример dl4.joxi.net/drive/2018/07/25/0008/3395/548163/63/… 25 июл 2018 в 12:00
  • @DigitalCore - как вы изменили положение в своем примере? 25 июл 2018 в 12:13

2 ответа 2

3

Вот такой можно сделать костыль (накидать пробелов перед тайтлом)! :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;
}
5
  • спасибо, думал, что это можно сделать проще, изменив какое-то свойство:) 25 июл 2018 в 13:26
  • @NovitskiyDenis разумней написать свой класс для формы с таким отображением))
    – yolosora
    25 июл 2018 в 13:29
  • 1
    А если на Win8 потом это запустить? (там заголовок как раз штатно по центру отображается): stackoverflow.com/q/11824181/6766879 25 июл 2018 в 13:44
  • @АндрейNOP var osVersion = Environment.OSVersion.Version; if (osVersion.Major == 6 && osVersion.Minor == 2) return; например так :D
    – yolosora
    25 июл 2018 в 13:57
  • 3
    Ну да, продолжим наращивать костыли! :D 25 июл 2018 в 13:58
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

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.