本文介绍了如何在单个单词中导航到上一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在单个单词中导航到上一个字母
how to navigate to previous letter in a single word
推荐答案
using System;
using System.Windows.Forms;
namespace NavigateToLetter
{
static class Program
{
[STAThread]
static void Main()
{
// Create a Form with a TextBox
Form form = new Form();
form.Text = "NavigateToLetter";
TextBox textbox = new TextBox();
textbox.Multiline = true;
textbox.Dock = DockStyle.Fill;
form.Controls.Add(textbox);
// We handle the PreviewKeyDown event to jump to a new cursor
// position on entered "input", this could be any key-combination
//(NUM block, function keys, letters, ...)
textbox.PreviewKeyDown +=
delegate(object sender, PreviewKeyDownEventArgs e)
{
// ... so how to control the jumping while typing -
// hmm.. lets take the function keys
const int iF1_KEY = 112; // the F1 key
const int iF24_KEY = 135; // the F24 key
//
int iKey = (int)e.KeyCode; // so grab the pressed key's code
// ... and look if it's a function key
// (we use the Keys enumaration values to shorten the code)
if (iKey >= iF1_KEY && // the F1 Key
iKey <= iF24_KEY) // the F24 Key (if you have a keyboard
// with that many Function-Keys)
{
string strWord = String.Empty; // the current word.
int iIndexOfLastSpace = textbox.Text.LastIndexOf(' ');
// Where is the last word?
if (iIndexOfLastSpace < 0) // no previous words found
{
// so we assume we are on the first word
strWord = textbox.Text;
}
else
{
// let's take the string starting from the last space as
//current word
strWord = textbox.Text.Substring(iIndexOfLastSpace + 1);
}
// do we have a word now?
if (!String.IsNullOrEmpty(strWord))
{
// lets think about the jumping:
// get the new cursor position the user gave us
int iEnteredPosition = iKey - iF1_KEY;
// but, is the word long enough?
// (else we stay on the current cursor position)
if (strWord.Length >= iEnteredPosition)
{
// calculate the new cursor position
// (begin of last word + entered position)
int iNewPosition = textbox.Text.Length -
strWord.Length + iEnteredPosition;
// and finally: set the cursor position
textbox.Select(iNewPosition, 0);
}
}
}
};
// Ok, let's run the form and test it!
Application.Run(form);
}
}
}
这篇关于如何在单个单词中导航到上一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!