There doesn't appear to be a simple mechanism to retrieve only the user entered data and after trying to solve this problem, I can understand why. What constitutes user entered data is not always clear and it seems that Microsoft has decided to not tackle that question.
I've decided to manually keep track of the user data by registering for a TextChanged
event. Since each key stroke will trigger this event, by keeping track of the previous value of Text
, I can determine if either an Append auto-complete or paste operation has occurred.
The code snippet below if from the TextChanged
event handler of my custom TextBox
class; UserText
contains the user entered data (of type string
).
if (string.IsNullOrEmpty(UserText) ||
UserText.Length > Text.Length ||
UserText.Length + 1 == Text.Length)
{
UpdateUserText(Text);
}
UpdateUserText(string)
first determines if a change has occurred, and if so, assigns the new value to UserText
and issues an event. In the case of a paste operation, one could use the solution posted here; however, I opted to do the following:
MouseClick += UpdateUserText;
KeyUp += UpdateUserText;
//--------------------------------------------------------
private void UpdateUserText(object sender, EventArgs args)
{
if (SelectionLength == 0)
{
UpdateUserText(Text);
}
}
In this way, if text in the TextBox
is no longer highlighted, then I assume it has become user entered text. This takes care of the paste operation (either via the keyboard or mouse) and caters for the user pressing the arrow keys in attempt to accept the auto-complete suggestion.
One of the edge cases that I decided to ignore is when the user has typed the entire word but the last character, in this case I would not be able to differentiate between the auto-complete suggestion and the user input.
I also considered using a StringBuilder
to manually keep track of the user entered data but I think that requires more effort than keeping track of the already constructed string
in Text
.
I'm always open to a better implementation if anyone has a suggestion :)