如何设置文本框点击时的光标位置

发布于 2024-08-20 02:05:49 字数 421 浏览 4 评论 0原文

我需要一个预先填充一些文本的文本框,并希望光标在聚焦时默认位于文本框的开头。

private void txtBox_Enter(object sender, EventArgs e)
{
    if (this.txtBox.Text == "SOME PREFILL TEXT")
    {
        this.txtBox.Select(0, 0);
    }
}

我正在捕获 _Enter ,如果我按 Tab 键进入文本框,它实际上会起作用,但是如果我用鼠标单击文本框,则光标会出现在执行鼠标单击的位置,表明它是在 _Enter 事件之后处理的,有效地“覆盖”我所做的事情。 为了解决这个问题,我连接了 _Click 事件来调用 txtBox_Enter 处理程序,但没有成功。

有解决办法吗?

谢谢, -本

I'm required to have a textbox pre-filled with some text, and want the cursor to default to the beginning of the textbox when it is focused.

private void txtBox_Enter(object sender, EventArgs e)
{
    if (this.txtBox.Text == "SOME PREFILL TEXT")
    {
        this.txtBox.Select(0, 0);
    }
}

I'm capturing _Enter as above and it actually does work if I tab into the text box, but if I mouse-click into the text box, the cursor appears wherever the mouse click was performed, indicating that it is handled after the _Enter event, effectively "overwriting" what I did.
To combat this, I hooked in the _Click event to call the txtBox_Enter handler as well, but no luck.

Is there any work around for this?

Thanks,
-Ben

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绝對不後悔。 2024-08-27 02:05:49

您想要完成什么 - 更改默认功能(例如通常会选择光标位置的单击)正在询问用户体验问题。

也许类似于 SETCUEBANNER 是您想要的吗?

What is it the you are trying to accomplish - changing default functionality (such as a click which would normally select the cursor location) is asking for User Experience problems..

Perhaps something along the lines of SETCUEBANNER is what you are trying for?

清风无影 2024-08-27 02:05:49

也许您可以将 if 块提取到它自己的方法中。

然后从 txtBox_Enter() 以及 _Click 或 _AfterClick()(如果存在)中调用它。

您还可以使用 _Focus() 事件进行调查,尽管我不确定它们按事件触发的顺序排列在哪里。

Perhaps you could extract your if block to it's own method.

Then call this from the txtBox_Enter() as well as either the _Click or, if it exists, _AfterClick()

You could also investigate using the _Focus() events, although I'm not sure where they fall in the order of events fired.

情深如许 2024-08-27 02:05:49

我还通过处理 _MouseClick 事件解决了这个问题。我使用 _Enter 事件来处理控制案例中的选项卡,并将相同的代码添加到 _MouseClick:

private void txtBox_MouseClick(object sender, EventArgs e)
{
    if (this.txtBox.Text == "SOME PREFILL TEXT")
    {
        this.txtBox.Select(0, 0);
    }
}

同时使用 _Enter 和 _MouseClick 事件应该可以满足您的需求。

I solved this issue by also handling the _MouseClick event. I used the _Enter event to handle the tab into the control case and added the same code to the _MouseClick:

private void txtBox_MouseClick(object sender, EventArgs e)
{
    if (this.txtBox.Text == "SOME PREFILL TEXT")
    {
        this.txtBox.Select(0, 0);
    }
}

Using both the _Enter and _MouseClick events should cover your needs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文