【问题标题】:Insert Text with a shortcut key使用快捷键插入文本
【发布时间】:2014-11-12 08:19:21
【问题描述】:

我一直在插入像“xx--xx--xx\username”这样的文本。所以我需要在按下 Alt/Ctrl + another key 后插入文本。

在阅读了一些关于这个问题的信息后,我发现了一些有用的信息:

How to detect the currently pressed key?

我不知道该怎么做。 任何其他人都应该根据需要定义自己的 'xx--xx--xx\username'。因此,下一步是将其保存到文件中。

Stack Overflow 上有没有关于这个问题的帖子?我找不到任何结果,可能是我搜索错误。

【问题讨论】:

  • 您要插入什么文本以及要在文本框中的哪个位置添加它,在前面还是后面?
  • 嗨 Bernd,我想插入一个网络路径,所以我需要一个字符串。我想在前面插入文本。按下文件夹中的按钮后,文本将被保存,因此每次我启动程序时都可以加载保存的文本。

标签: c# text insert onkeydown


【解决方案1】:

要捕获KeyDown 事件以检测用户是否按下了快捷键,请使用此代码处理事件KeyDown(其中txtInputTextBox

this.txtInput.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtInput_KeyDown);

现在创建提到的方法 (txtInput_KeyDown) 并添加以下代码来处理特定的快捷方式
(PS要在VisualStudio中处理事件并创建方法,只需双击属性中的KeyDown即可)

// Shortcut Alt+I
if (e.Alt && (e.KeyCode == Keys.I))
{
  txtInput.Text = @"somedomain\" + txtInput.Text; // Adds the text to the front of the current text
  txtInput.SelectionStart = txtInput.Text.Length; // Sets the cursor to the end of the text
}
// Shortcut Ctrl+K
else if (e.Control && (e.KeyCode == Keys.K))
{
  txtInput.Text += @"networkpath\"; // Adds the text to the back of the current text
  txtInput.SelectionStart = txtInput.Text.Length; // Sets the cursor to the end of the text
}

如代码中的cmets所述,这段代码会对两种不同的快捷键组合进行不同的处理,根据自己的需要进行修改。

可以通过here 对 KeyDown 事件进行额外阅读。

您提到的下一步是保存信息并在应用程序再次启动时加载它,阅读关于存储和检索用户设置的 SO 帖子 herehere

有关用户设置的 MSDN 条目:
Using Application Settings and User Settings
How To: Write User Settings at Run Time with C#
Using Settings in C#

【讨论】:

  • 谢谢。也许我不够清楚。对此感到抱歉,但我可以将路径放入另一个窗口,如远程连接窗口。所以我的工具应该在后台工作,每当我按下像 alt + i 这样定义的键时,它应该将它插入到我的鼠标/前窗口所在的字段中。
  • 这将需要在应用程序之间传递 Windows 消息,我建议您对此进行一些研究,并在遇到困难时发布一个单独的问题
猜你喜欢
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 2015-04-13
  • 2016-01-24
相关资源
最近更新 更多