• 设置字体垂直居中

    2012-08-20 17:20:41
    1、m_pStatic-> ModifyStyle(0, SS_CENTERIMAGE);   2、CStatic *cs; ... cs = new CStatic(); cs-> Create( "hello world ",  WS_CHILD|WS_VISIBLE|SS_CENTER,  CRect(50,80,
    1、m_pStatic-> ModifyStyle(0,   SS_CENTERIMAGE);
     
    2、CStatic   *cs;
    ...
    cs   =   new   CStatic();
    cs-> Create( "hello   world ",
          WS_CHILD|WS_VISIBLE|SS_CENTER,
          CRect(50,80,   150,   150),
          this);
    展开全文
  • C# excel 单元格居中

    2019-10-08 05:51:04
    C#操作excel //导出Excel private void ExportExcel(string fileName, System.Data.DataTable myDGV, string title) { string saveFileName = ""; System.Windows.Forms...

    C# 操作excel

    //导出Excel
            private void ExportExcel(string fileName, System.Data.DataTable myDGV, string title)
            {
                string saveFileName = "";
                System.Windows.Forms.SaveFileDialog saveDialog = new System.Windows.Forms.SaveFileDialog();
                saveDialog.DefaultExt = "xlsx";
                saveDialog.Filter = "Excel文件|*.xlsx";
                saveDialog.FileName = fileName;
                saveDialog.ShowDialog();
                saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0) return; //被点了取消
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (xlApp == null)
                {
                    System.Windows.MessageBox.Show("无法创建Excel对象,可能您的电脑未安装Excel");
                    return;
                }
                Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
                Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1

                //操作单元格
                Range rangeLecture = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, myDGV.Columns.Count]];
                rangeLecture.Application.DisplayAlerts = false;
                rangeLecture.Merge(Missing.Value);
                rangeLecture.Application.DisplayAlerts = true;
                worksheet.Cells[1, 1] = title;
               

                //写入标题
                for (int i = 0; i < myDGV.Columns.Count; i++)
                {
                    worksheet.Cells[2, i + 1] = myDGV.Columns[i].ColumnName;
                }
                //写入数值
                for (int r = 0; r < myDGV.Rows.Count; r++)
                {
                    for (int i = 0; i < myDGV.Columns.Count; i++)
                    {
                        worksheet.Cells[r + 3, i + 1] = myDGV.Rows[r][i].ToString();
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
                if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;
                        workbook.SaveCopyAs(saveFileName);
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                    }
                }
                xlApp.Quit();
                GC.Collect();//强行销毁
                //System.Windows.Forms.MessageBox.Show("文件保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

     

    操作单元格样式

    worksheet.Cells[1, 1].Value2 = strTitle; //设置单元格内文本  

    worksheet.Cells[1, 1].Font.Name = "宋体";//设置字体  

    worksheet.Cells[1, 1].Font.Size = 18;//字体大小  

    worksheet.Cells[1, 1].Font.Bold = true;//加粗显示  

    worksheet.Cells[1, 1].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中  

    worksheet.Cells[1, 1].VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;//垂直居中  

    worksheet.Cells[1, 1].Borders.LineStyle = Excel.XlLineStyle.xlContinuous;//设置边框  

    worksheet.Cells[1, 1].Borders.Weight = Excel.XlBorderWeight.xlMedium;//边框常规粗细  

     

    转载于:https://www.cnblogs.com/chendongbky/p/6210712.html

    展开全文
  • 想要把其中的文本设置为居中但是没有直接方法; 方案一:网上流传比较多方法: 第一步:先将combobox的DrawMode属性设置为OwnerDrawFixed; 第二步:在comboBox的DrawItem事件方法中重新绘制item选项的位置;这里...
    • 在原生的ComboBox功能中没有属性是设置文本位置,默认位置为左对齐;想要把其中的文本设置为居中但是没有直接方法;

    • 方案一:网上流传比较多方法:
      第一步:先将combobox的DrawMode属性设置为OwnerDrawFixed; 在这里插入图片描述
      第二步:在comboBox的DrawItem事件方法中重新绘制item选项的位置;这里不做细说,附网址https://zhidao.baidu.com/question/143123179.html
      在这里插入图片描述
      但是这种方法有一个弊端:居中的只是下拉项;而显示区域的文本不会居中;
      So作者又进行了第三步:给显示区域的文本进行居中;方法是
      //字符所占空间大小方法,用于求空格宽度和选项字符串宽度; Font是字符串的样式
      Graphics graphics = CreateGraphics();
      SizeF size_item = graphics.MeasureString(“ ”, Font);

      剩余宽度=(控件宽(可知)-文本宽(可知))/2;
      空格个数=剩余宽度/空格宽度;
      显示项=(空格个数*n )拼接+原文本.Trim();

    问题:1、不能正确居中,把空格换成“-”就行,想不通;
    2、在选择其他选项后显示文本又变成左对齐(自动把添加的空格去掉了);
    3、在SelectIndex事件中给Items重新复制会导致 死循环!!!!

    • 方案二:踏过前面的坑,想直接在初始化时候就根据宽度给每个选择项都添加空格设置居中;
      上代码
    	        float w1 = comboBox1.Width;
                comboBox1.SelectedIndex=0;
                Graphics graphics = CreateGraphics();
                SizeF sizeF_sp = graphics.MeasureString(" ", comboBox1.Font);						//空格宽度
                for (int i = 0; i < comboBox1.Items.Count; i++)
                {
                    SizeF sizeF_1 = graphics.MeasureString(comboBox1.Items[i].ToString().Trim(), comboBox1.Font);      // 选中字宽度
                    int spmun = (int)(((w1 - sizeF_1.Width) / 2) / sizeF_sp.Width);
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < spmun; j++)
                    {
                        sb.Append(" ");
                    }
                    sb.Append(comboBox1.Items[i].ToString());
                    comboBox1.Items[i] = sb.ToString();
                }  
    
    • 还有就是直接重绘,每次选择项之后,在SelectIndex_Changed 或者SelectValue_Changed中重新绘制我没 有进行尝试,有试过的朋友可以进行留言;
    展开全文
  • Font titleFont = new Font("新宋体", 10, FontStyle.Bold);//字体 Brush brush = new SolidBrush(Color.Black);//画刷 Point po = new Point(10, 10); //坐标 float left = e.PageSettings.Margins.Left...
  • C#如何实现打印居中

    2010-09-19 15:09:00
    //实现横向居中PrintPageEventArgs e; StringFormat SF = new StringFormat();SF.LineAlignment = StringAlignment.Center; //设置属性为水平居中SF.Alignment = StringAlignment.Center; 

    //实现横向居中

    PrintPageEventArgs e;            

    StringFormat SF = new StringFormat();
    SF.LineAlignment = StringAlignment.Center;                                        //设置属性为水平居中
    SF.Alignment = StringAlignment.Center;                                               //设置属性为垂直居中
     RectangleF rect = new RectangleF(0,0,e.PageBounds.Width,e.Graphics.MeasureString("Authors Informations",new Font("Times New Roman",20)).Height);    //其中e.PageBounds属性表示页面全部区域的矩形区域

    e.Graphics.MeasureString(string,Font).Height

    //表示获取你要打印字符串的高度

     e.Graphics.DrawString("Authors Informations",new Font("Times New Roman",20),Brushes.Black,rect,SF);

    展开全文
  • 原生的TextBox不支持文本的垂直居中及Padding功能,今天晚上抽时间搞了一下,此代码主要为增加这些功能。与大家共享。 using System;using System.Collections.Generic;using System.ComponentModel;using System...

    原生的TextBox不支持文本的垂直居中及Padding功能,今天晚上抽时间搞了一下,此代码主要为增加这些功能。与大家共享。

     

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Windows.Forms;

    namespace TextBoxEx
    {
        public partial class TextBoxEx : TextBox
        {
            //设置Rect消息
            private const int EM_SETRECT = 179;
            //获取Rect消息
            private const int EM_GETRECT = 178;
            //private const int WM_GETTEXT = 0x000d;
            //private const int WM_COPY = 0x0301;
            //粘贴消息
            private const int WM_PASTE = 0x0302;
            //绘制消息
            private const int WM_PAINT = 0xF;
            //控件颜色编辑消息
            private const int WM_CTLCOLOREDIT = 0x0133;
            //private const int WM_CONTEXTMENU = 0x007B;
            //private const int WM_RBUTTONDOWN = 0x0204;

            public TextBoxEx()
            {
                InitializeComponent();
                //this.SetStyle(ControlStyles.UserPaint
                //    | ControlStyles.DoubleBuffer
                //    | ControlStyles.ResizeRedraw  //调整大小时重绘
                //    | ControlStyles.AllPaintingInWmPaint // 禁止擦除背景.
                //    | ControlStyles.OptimizedDoubleBuffer // 双缓冲
                //    | ControlStyles.SupportsTransparentBackColor //透明效果
                //    , true);
                //多行显示 只有多行显示才能设置Rect有效
                this.Multiline = true;
                //不允许回国
                AllowReturn = false;
                //关闭默认的边框
                BorderStyle = System.Windows.Forms.BorderStyle.None;
                //禁止折行
                WordWrap = false;

                _textMargin = new Padding(1);
            }

            protected override void OnResize(EventArgs e)
            {
                base.OnResize(e);
                SetTextDispLayout();
            }

            protected override void OnTextAlignChanged(EventArgs e)
            {
                base.OnTextAlignChanged(e);
                SetTextDispLayout();
            }

            protected override void OnKeyPress(KeyPressEventArgs e)
            {
                //如果不允许回车 屏蔽回车 换行键值
                if (!AllowReturn
                    && ((int)e.KeyChar == (int)Keys.Return || (int)e.KeyChar == (int)Keys.LineFeed))
                {
                    e.Handled = true;
                }
                base.OnKeyPress(e);
            }

            /// <summary>
            /// 绘制消息进行绘制边框
            /// </summary>
            /// <param name="m"></param>
            private void WmPaint(ref System.Windows.Forms.Message m)
            {

                if (ClientRectangle.Width > 0 && ClientRectangle.Height > 0)
                {
                    Rectangle clientRect = this.ClientRectangle;

                    Color lineColor = borderRenderStyle.LineColor;
                    if (Focused)
                        lineColor = borderRenderStyle.ActiveLineColor;
                    using (Graphics g = this.CreateGraphics())
                    {
                        if (clientRect.Width > 0 && clientRect.Height > 0)
                        {
                            using (Pen pen = new Pen(lineColor, borderRenderStyle.LineWidth))
                            {
                                pen.DashStyle = borderRenderStyle.LineDashStyle;
                                if (borderRenderStyle.ShowLeftLine)
                                {
                                    g.DrawLine(pen, clientRect.Location, new Point(clientRect.Left, clientRect.Bottom));
                                }

                                if (borderRenderStyle.ShowTopLine)
                                {
                                    g.DrawLine(pen, clientRect.Location, new Point(clientRect.Right, clientRect.Top));
                                }

                                if (borderRenderStyle.ShowRightLine)
                                {
                                    g.DrawLine(pen, new Point(clientRect.Right - 1, clientRect.Top), new Point(clientRect.Right - 1, clientRect.Bottom));
                                }

                                if (borderRenderStyle.ShowBottomLine)
                                {
                                    g.DrawLine(pen, new Point(clientRect.Left, clientRect.Bottom - 1), new Point(clientRect.Right, clientRect.Bottom - 1));

                                }
                            }
                        }
                    }
                }

     

            }

            /// <summary>
            /// 窗体处理消息主函数 处理粘贴及绘制消息
            /// </summary>
            /// <param name="m"></param>
            protected override void WndProc(ref System.Windows.Forms.Message m)
            {
                string str = "";
                bool flag = false;
                int i = 0;
                if (m.Msg == 0x0204)
                    i++;
                if (!AllowReturn
                    && m.Msg == WM_PASTE
                    && System.Windows.Forms.Clipboard.ContainsText())
                {
                    str = System.Windows.Forms.Clipboard.GetText();
                    System.Windows.Forms.Clipboard.Clear();
                    string nstr = str.Replace(char.ConvertFromUtf32((int)Keys.Return), "").Replace(char.ConvertFromUtf32((int)Keys.LineFeed), "");
                    System.Windows.Forms.Clipboard.SetText(nstr);
                    if (str.Length > 0) flag = true;
                }


                base.WndProc(ref m);
                if (flag)
                {
                    flag = false;
                    System.Windows.Forms.Clipboard.SetText(str);
                    str = "";
                }

                if (m.Msg == WM_PAINT || m.Msg == WM_CTLCOLOREDIT)
                {
                    WmPaint(ref m);
                }
            }


            [DllImport("user32.dll", EntryPoint = "SendMessageA")]
            private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, string lParam);

            [DllImport("user32.dll", EntryPoint = "SendMessageA")]
            private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref Rectangle lParam);

            /// <summary>
            /// 尺寸变化时重新设置字体的显示位置居中
            /// </summary>
            /// <param name="e"></param>
            protected override void OnSizeChanged(EventArgs e)
            {
                base.OnSizeChanged(e);
                SetTextDispLayout();
            }

            /// <summary>
            /// 设置文本显示布局位置
            /// </summary>
            public void SetTextDispLayout()
            {
                if (Text == "")
                    return;
                Rectangle rect = new Rectangle();
                SendMessage(this.Handle, EM_GETRECT, (IntPtr)0, ref rect);
                SizeF size = CreateGraphics().MeasureString(Text, Font);
                rect.Y = (int)(Height - size.Height) / 2 + TextMargin.Top;
                rect.X = 1 + TextMargin.Left;
                rect.Height = Height - 2;
                rect.Width = Width - TextMargin.Right - TextMargin.Left - 2;
                SendMessage(this.Handle, EM_SETRECT, IntPtr.Zero, ref rect);
            }

            /// <summary>
            /// 边框样式
            /// </summary>
            /// <remarks>获取或设置边框样式.</remarks>
            [Category("Appearance"),
             Description("边框样式"),
             DefaultValue(null)]
            public virtual TTextBoxBorderRenderStyle BorderRenderStyle
            {
                get { return borderRenderStyle; }
                set { borderRenderStyle = value; }
            }
            private TTextBoxBorderRenderStyle borderRenderStyle = new TTextBoxBorderRenderStyle();

            /// <summary>
            /// 是否允许有回车
            /// </summary>
            public bool AllowReturn { get; set; }

            protected override void OnTextChanged(EventArgs e)
            {
                base.OnTextChanged(e);

                SetTextDispLayout();
            }

            private Padding _textMargin;
            /// <summary>
            /// Text Padding值
            /// </summary>
            public Padding TextMargin { get { return _textMargin; } set { _textMargin = value; SetTextDispLayout(); } }
        }

        [TypeConverter(typeof(ExpandableObjectConverter))]
        public class TTextBoxBorderRenderStyle
        {
            /// <summary>
            /// 边线颜色
            /// </summary>
            /// <remarks>获取或设置边线颜色</remarks>
            [Category("Appearance"),
             Description("获取或设置边线颜色"),
             DefaultValue(typeof(Color), "Gray")]
            public virtual Color LineColor
            {
                get { return gridLineColor; }
                set { gridLineColor = value; }
            }
            private Color gridLineColor = Color.LightGray;

            /// <summary>
            /// 激活状态时的边线颜色
            /// </summary>
            /// <remarks>获取或设置激活状态时的边线颜色.</remarks>
            [Category("Appearance"),
             Description("激活状态时的边线颜色"),
             DefaultValue(typeof(Color), "RoyalBlue")]
            public virtual Color ActiveLineColor
            {
                get { return activeGridLineColor; }
                set { activeGridLineColor = value; }
            }
            private Color activeGridLineColor = Color.RoyalBlue;

            [Category("Appearance"),
             Description("线宽度"),
             DefaultValue(1)]
            public virtual float LineWidth
            {
                get { return lineWidth; }
                set { lineWidth = value; }
            }
            private float lineWidth = 1;

            /// <summary>
            ///线样式
            /// </summary>
            /// <remarks>获取或设置线样式.</remarks>
            [Category("Appearance"),
             Description("获取或设置线样式"),
             DefaultValue(typeof(DashStyle), "Solid")]
            public virtual DashStyle LineDashStyle
            {
                get { return lineDashStyle; }
                set { lineDashStyle = value; }
            }
            private DashStyle lineDashStyle = DashStyle.Solid;

            /// <summary>
            /// 左边线是否显示
            /// </summary>
            /// <remarks>获取或设置左线是否显示.</remarks>
            [Category("Appearance"),
             Description("左边网格线是否显示"),
            DefaultValue(true)
            ]
            public virtual bool ShowLeftLine
            {
                get { return showLeftLine; }
                set { showLeftLine = value; }
            }
            private bool showLeftLine = true;

            /// <summary>
            /// 上边线是否显示
            /// </summary>
            /// <remarks>获取或设置上边线是否显示.</remarks>
            [Category("Appearance"),
             Description("上边线是否显示"),
            DefaultValue(true)
            ]
            public virtual bool ShowTopLine
            {
                get { return showTopLine; }
                set { showTopLine = value; }
            }
            private bool showTopLine = true;

            /// <summary>
            /// 右边线是否显示
            /// </summary>
            /// <remarks>获取或设置右边线是否显示.</remarks>
            [Category("Appearance"),
             Description("右边线是否显示"),
            DefaultValue(true)
            ]
            public virtual bool ShowRightLine
            {
                get { return showRightLine; }
                set { showRightLine = value; }
            }
            private bool showRightLine = true;

            /// <summary>
            /// 底边线是否显
            /// </summary>
            /// <remarks>获取或设置底边线是否显示.</remarks>
            [Category("Appearance"),
             Description("底边线是否显示"),
            DefaultValue(true)
            ]
            public virtual bool ShowBottomLine
            {
                get { return showBottomLine; }
                set { showBottomLine = value; }
            }
            private bool showBottomLine = true;

        }
    }

    转载于:https://www.cnblogs.com/jason_chen/p/6291295.html

    展开全文
  • c#窗体标题文本居中

    2020-04-11 21:14:53
    //Graphics g = this.CreateGraphics();... //Double startingPoint = (this.Width / 2) - (g.MeasureString(this.Text.Trim(), this.Font).Width / 2); //Double ws = g.MeasureString("*", t...
  • 最近项目中又需要客制化一些控件,draw来draw去真的好烦,其中有ListBox客制化并居中显示字体,特记录下供各位以备不时,比较简单,禁止拍砖哈~~~ 首先将Listbox的DrawMode属性设置为DrawMode....
  • private void groupBox1_Paint(object sender, PaintEventArgs e) { e.Graphics.Clear(groupBox1.BackColor); SizeF fontSize = e.Graphics.MeasureString(groupBox1.Text, groupBo
  • 感谢他们给的启发 这位 这位 Microsoft.Office.Interop.Word.Table newTable = xxx.wordDoc.Tables.Add(xxx.app.Selection.Range, 1, 7, ref oMissing, ref oMissing); newTable.Borders.OutsideLineStyle = ...
  • 1、首先设置DrawMode属性为OwnerDrawVariable 2、 增加事件重画ListBox private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); ...e.DrawFocusRectangle();...
  • 编辑列-〉找到有你想居中的列-〉样式里面的ItemStyle -〉Font里面的HorizontalAlign是使设置水平对其的属性的,VerticalAlign是设置竖直对其方式的。
  • public partial class PubTextBox : TextBox  {  //设置Rect消息  private const int EM_SETRECT = 179;  //获取Rect消息  private const int EM_GETRECT = 178;  //粘贴消息  pr...
  • C#中使用DrawString绘制文本时的对齐方式 C#代码: void 绘制文字(Graphics 画家) { StringFormat 格式 = new StringFormat(); 格式.Alignment = StringAlignment.Center; //居中 格式.Alignment = String...
  • #region &lt;&lt;单元格合并配置&gt;&gt; public struct MergeCellsParam { public int iStartCellColumn; public int iStartCellRow; public int iEndCellColumn; ...
  • 方式一:单行文本垂直居中 其实单行文本垂直居中是垂直居中中最为简单的了。通常使用line-height 和 height配合使用即可,也就是将line-height和height设置为同样的数值。 当然也有道友说其实这个地方设置height值...
  • GDI+文本居中

    2015-08-30 15:59:31
    FontFamily l_formatFont(L"宋体");  //字体格式 Gdiplus::Font l_font(&l_formatFont, 18, FontStyleRegular, UnitPixel); //文字居中 StringFormat l_formatRect;  l_formatRect.SetAlignment(StringAlignme
  • private void groupBox1_Paint(object sender, PaintEventArgs e) { //e.Graphics.Clear(Color.Transparent); //SizeF fontSize = e.Graphics.MeasureString(groupBox1.Te...
  •  一、 以lable为例:    在Form中放一个控件,让其在启动和动态改变窗口大小时始终居中    int gLeft = this.Width / 2 - lable1.Width / 2; //this指Form  int gTop = this....
  • Form的text 居中显示

    2018-09-25 10:11:29
    Graphics g = this.CreateGraphics(); //光标居中 Double startingPoint = (this.Width / 2) - (g.MeasureString(this.Text.Trim(), this.Font).Width / 2); Double ws = g.Measur...
1 2 3 4 5 ... 20
收藏数 4,210
精华内容 1,684
热门标签