How to set the TAB width in a Windows Forms TextBox control?

前端 未结 6 498
独厮守ぢ
独厮守ぢ 2020-12-17 08:57

Given a WinForms TextBox control with MultiLine = true and AcceptsTab == true, how can I set the width of the tab character displayed?

I wa

6条回答
  •  攒了一身酷
    2020-12-17 09:33

    With the use of extension methods, you can add a new method to the TextBox control class. This is my implementation (including an additional extension method that gives you the coordinates for the current location of the insert caret) from what I gathered from the previous contributors above:

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    namespace Extensions
    {
        public static class TextBoxExtension
        {
            private const int EM_SETTABSTOPS = 0x00CB;
    
            [DllImport("User32.dll", CharSet = CharSet.Auto)]
            private static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);
    
            public static Point GetCaretPosition(this TextBox textBox)
            {
                Point point = new Point(0, 0);
    
                if (textBox.Focused)
                {
                    point.X = textBox.SelectionStart - textBox.GetFirstCharIndexOfCurrentLine() + 1;
                    point.Y = textBox.GetLineFromCharIndex(textBox.SelectionStart) + 1;
                }
    
                return point;
            }
    
            public static void SetTabStopWidth(this TextBox textbox, int width)
            {
                SendMessage(textbox.Handle, EM_SETTABSTOPS, 1, new int[] { width * 4 });
            }
        }
    }
    

提交回复
热议问题