C# WinForms 文本框的自定义插入符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/609927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom Caret for WinForms TextBox
提问by Rogier
I'm developing a custom HyperTerminal like application in a WinForms .Net 2.0 application. I have a multiline TextBox in a Panel in which you can interact with a hardware device.
我正在 WinForms .Net 2.0 应用程序中开发一个自定义的 HyperTerminal 之类的应用程序。我在面板中有一个多行文本框,您可以在其中与硬件设备进行交互。
My customer wants to have a custom Caret, a filled rectangle the size of one character space instead of the vertical line that is by default.
我的客户想要一个自定义的 Caret,一个填充的矩形,大小为一个字符空间,而不是默认情况下的垂直线。
I know .Net does not provide an option to do this by default, but there must some Windows function to do it.
我知道 .Net 默认不提供执行此操作的选项,但必须有一些 Windows 功能才能执行此操作。
采纳答案by Julian de Wit
Assume a form with a textbox on it:
假设一个带有文本框的表单:
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
[DllImport("user32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
CreateCaret(textBox1.Handle, IntPtr.Zero, 10, textBox1.Height);
ShowCaret(textBox1.Handle);
}
}
回答by Peter Gfader
I would use System.Drawing to draw a custom cursor (bitmap), maybe with a timer to let it blink like another cursor.
我会使用 System.Drawing 来绘制一个自定义光标(位图),也许用一个计时器让它像另一个光标一样闪烁。
Get the current position of the Cursor in pixels and draw a bitmap over that cursor. Can be tricky to find the correct position, but should be doable.
以像素为单位获取光标的当前位置并在该光标上绘制位图。找到正确的位置可能很棘手,但应该是可行的。
Have a look here for Owner drawn textbox in winforms.
在此处查看winforms 中所有者绘制的文本框。
回答by NileshChauhan
These are the list of Native Caret functions provided by Windows you can use them for you application.
这些是 Windows 提供的本地 Caret 函数列表,您可以将它们用于您的应用程序。
[DllImport("User32.dll")]
static extern bool CreateCaret(IntPtr hWnd, int hBitmap, int nWidth, int nHeight);
[DllImport("User32.dll")]
static extern bool SetCaretPos(int x, int y);
[DllImport("User32.dll")]
static extern bool DestroyCaret();
[DllImport("User32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
[DllImport("User32.dll")]
static extern bool HideCaret(IntPtr hWnd);
Refer SharpDevelop, Source Code @ src\Libraries\ICSharpCode.TextEditor\Project\Src\Gui\Caret.cs
参考SharpDevelop,源代码@src\Libraries\ICSharpCode.TextEditor\Project\Src\Gui\Caret.cs
回答by Tom E.
Use:
用:
richTextBoxConsole.GetPositionFromCharIndex(cursorPos)
Hide the normal caret and draw your own? Not tested, but should work I think.
隐藏正常的插入符号并绘制自己的插入符号?未经测试,但我认为应该可以工作。