考虑到与一个WinForms TextBox控件MultiLine = true
和AcceptsTab == true
,我怎么可以设置制表符的宽度显示?
我想用这个作为一个插件一个快速和肮脏的脚本输入框。 这真的并不需要在所有的花哨,但如果标签没有显示为宽8个字符就好...
考虑到与一个WinForms TextBox控件MultiLine = true
和AcceptsTab == true
,我怎么可以设置制表符的宽度显示?
我想用这个作为一个插件一个快速和肮脏的脚本输入框。 这真的并不需要在所有的花哨,但如果标签没有显示为宽8个字符就好...
我想发送EM_SETTABSTOPS
消息到文本框会工作。
// set tab stops to a width of 4
private const int EM_SETTABSTOPS = 0x00CB;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);
public static void SetTabWidth(TextBox textbox, int tabWidth)
{
Graphics graphics = textbox.CreateGraphics();
var characterWidth = (int)graphics.MeasureString("M", textbox.Font).Width;
SendMessage
( textbox.Handle
, EM_SETTABSTOPS
, 1
, new int[] { tabWidth * characterWidth }
);
}
你可以在你的构造函数被调用Form
,但要注意:确保InitializeComponents
首先运行。
我知道你正在使用TextBox
当前,但如果你能逃脱使用RichTextBox
,而不是,那么你可以使用SelectedTabs属性设置所需的选项卡宽度:
richTextBox.SelectionTabs = new int[] { 15, 30, 45, 60, 75};
请注意,这些补偿是像素,而不是字符。
所提供的示例不正确。
所述EM_SETTABSTOPS
消息预计要被指定的标签尺寸对话框模板单元 ,而不是在像素。 一些周围挖后,将出现一个对话框模板单位,等于1/4号窗口的字符的平均宽度 。 所以你需要指定8 2个字符的标签,16四charachters,等等。
因此,代码可以简化为:
public static void SetTabWidth(TextBox textbox, int tabWidth)
{
SendMessage(textbox.Handle, EM_SETTABSTOPS, 1,
new int[] { tabWidth * 4 });
}
随着使用的扩展方法,你可以添加到TextBox控件类的新方法。 这是我的执行(包括为您提供了插入符的当前位置坐标的附加扩展方法),从我从上面以前贡献者云集:
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 });
}
}
}
谁想要不同的标签宽度,我把这个方法:
using System.Runtime.InteropServices;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, uint[] lParam);
private const int EM_SETTABSTOPS = 0x00CB;
private void InitialiseTabStops()
{
// Declare relative tab stops in character widths
var tabs = new uint[] { 2, 2, 4, 8, 2, 32 };
// Convert from character width to 1/4 character width
for (int position = 0; position < tabs.Length; position++)
tabs[position] *= 4;
// Convert from relative to absolute positions
for (int position = 1; position < tabs.Length; position++)
tabs[position] += tabs[position - 1];
SendMessage(textBox.Handle, EM_SETTABSTOPS, tabs.Length, tabs);
}
这是非常有用的:
对于一个多行TextBox控件设置的制表位位置