C# 防止在文本框中闪烁光标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/601255/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:51:52  来源:igfitidea点击:

Prevent Blinking Cursor in Textbox

c#winformstextbox

提问by Avik

In a textbox, how can u prevent the display of the blinking cursor when you click on it?

在文本框中,如何防止在单击时显示闪烁的光标?

I did read in some forums that there is call to a particular api but when i tried it in my code, an error was shown. Please provide the complete code for this purpose if possible and let me know if there is a particular event where the code should be executed.

我确实在一些论坛上读到有对特定 api 的调用,但是当我在我的代码中尝试它时,显示了一个错误。如果可能,请提供用于此目的的完整代码,并让我知道是否存在应执行代码的特定事件。

This textbox is part of a form window that am creating for the simulation of a lan messenger. I am using C#. The form has two textboxes in order to resemble that of google talk. It would be desirable to prevent displaying the blinking cursor on the upper textbox.

此文本框是为模拟 LAN 信使而创建的表单窗口的一部分。我正在使用 C#。该表单有两个文本框,以类似于 google talk 的文本框。最好防止在上部文本框上显示闪烁的光标。

I tried:

我试过:

[DllImport("user32")] 
private static extern bool HideCaret(IntPtr hWnd); 
public void HideCaret() { HideCaret(TextBox1.Handle); } 

I get the error: "DllImport could not be found."

我收到错误消息:“找不到 DllImport。”

回答by Eric Schoonover

Set the ReadOnlyproperty on the TextBoxto true.

将 上的ReadOnly属性设置TextBoxtrue

More answers to this question: Read-only textbox in C#

此问题的更多答案:C# 中的只读文本框

回答by Judah Gabriel Himango

If you want to disallow editing on the textbox, set it's ReadOnly property to true.

如果您想禁止对文本框进行编辑,请将其 ReadOnly 属性设置为 true。

If you want to allow editing but still hide the caret, call the Win32 API exactly as specified:

如果您想允许编辑但仍隐藏插入符号,请完全按照指定调用 Win32 API :

[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);

...

HideCaret(myTextBox.Handle);

回答by Olegan

VB.NET Code

VB.NET 代码

Imports System.Runtime.InteropServices

Public Class xxxxxxxxxxxxxxxxxxxxxx

<DllImport("user32.dll")>
    Private Shared Function HideCaret(ByVal hwnd As IntPtr) As Boolean
    End Function

...............

Private Sub txtNotePreview_MouseMove(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNotePreview.MouseMove, txtNotePreview.KeyPress
        HideCaret(txtNotePreview.Handle)
    End Sub

回答by Ali Reza Kalantar

Hi, Try this code

你好,试试这个代码

public class CustomTextBox:System.Windows.Forms.TextBox
{
    [System.Runtime.InteropServices.DllImport("user32")]
    private static extern bool HideCaret(IntPtr hWnd);

    public CustomTextBox()
    {
        TabStop = false;

        MouseDown += new System.Windows.Forms.MouseEventHandler(CustomTextBox_MouseDown);
    }

    void CustomTextBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        HideCaret(this.Handle);
    }
}

回答by kral06

Putting the hideCaret function inside the TextChanged event will solve the problem:

将 hideCaret 函数放在 TextChanged 事件中将解决问题:

[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);

private void textBox1_TextChanged(object sender, EventArgs e)
{
    HideCaret(textBox1.Handle);
}

回答by WhySoSerious

I am able to emulate Chrome's web address bar (partially) on a TextBoxusing code from both here and this answer.

我能够在TextBox来自此处和此答案的使用代码上模拟 Chrome 的网址栏(部分)。

On first click, it selects all the the text without showing the blinking caret, the trick is to make the caret show itself when you click a second time on the selected text, which is how Chrome's web address bar behaves.

第一次单击时,它会选择所有文本而不显示闪烁的插入符号,诀窍是在您第二次单击所选文本时使插入符号自行显示,这就是 Chrome 的网络地址栏的行为方式。

Here's the code:

这是代码:

[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);

private void textBox2_Enter(object sender, EventArgs e)
{
    // Kick off SelectAll asyncronously so that it occurs after Click
    BeginInvoke((Action)delegate
    {
        HideCaret(textBox2.Handle); 
        textBox2.SelectAll();              
    });          
}

回答by Chris Raisin

Others have stated that setting "ReadOnly" to "True" will avoid the caret when you click on a textbox. They are mistaken there. I am using VB.Net but maybe my sample code below might provide a simpler answer.

其他人表示,将“ReadOnly”设置为“True”将在您单击文本框时避免插入符号。他们在那里弄错了。我正在使用 VB.Net 但也许我下面的示例代码可能会提供一个更简单的答案。

It involves creating a new class (MyTextBox) with the added property of "NoCaret" which defaults to "False" (i.e. it shows caret by default). Add the following code to your project in a new class module, rebuild the project, then drag your new textbox (then found at top of your Toolbox) onto your form. To stop the caret showing tick "NoCaret" in the properties panel for each MyTextbox control you add to your forms.

它涉及创建一个新类 (MyTextBox),其中添加了“NoCaret”属性,该属性默认为“False”(即默认情况下显示插入符号)。将以下代码添加到您的项目的新类模块中,重建项目,然后将您的新文本框(然后在您的工具箱顶部找到)拖到您的表单上。要停止在您添加到表单的每个 MyTextbox 控件的属性面板中勾选“NoCaret”的插入符号。

So, you start by creating a new Class Module as follows (drawing the textbox in the designer is not necessary. It is actually better NOT to draw it since that will create unnecessary "InitializeComponent" code that will just muddy the waters. The line "MyBase.New()" in the sub "New()" takes care of everything)

因此,您首先按如下方式创建一个新的类模块(在设计器中绘制文本框不是必需的。实际上最好不要绘制它,因为这会创建不必要的“InitializeComponent”代码,只会使水域变得混乱。行“子“New()”中的MyBase.New()”负责一切)

Imports System.Runtime.InteropServices

Public Class MyTextBox
    Inherits TextBox
    Private Declare Function HideCaret Lib "user32.dll" (ByVal hwnd As Int32) As Int32
    Private Declare Function ShowCaret Lib "user32.dll" (ByVal hwnd As Int32) As Int32

    Private _HideCaret As Boolean

    Public Sub New()
        MyBase.New()
    End Sub

    Public Property NoCaret As Boolean
        Get
            Return _HideCaret
        End Get
        Set(ByVal value As Boolean)
            _HideCaret = value
        End Set
    End Property

    Private Sub TextBox_MouseMove(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.MouseMove
        If Me.NoCaret = True Then
            HideCaret(Handle.ToInt32)
        Else
            ShowCaret(Handle.ToInt32)
        End If
    End Sub
End Class

Make sure, though, that any EXISTING code that is making a "TypeOf" test on any existing textboxes on your form such as:

但是,请确保对表单上的任何现有文本框进行“TypeOf”测试的任何现有代码,例如:

For each tb as control in MyForm.Controls
   if TypeOf tb Is TextBox then
   .....{do something}
   endif
Next

is changed to:

改为:

For each tb as control in MyForm.Controls
   if TypeOf tb.Parent Is TextBox then
   .....{do something}
   endif
Next