RichTextBox Text Events - c#

I am getting a VERY annoying behavior trying to use the WPF RichTextBox events for some text manipulation.
The idea is to have some logic that will extract the RichTextBox text once some criteria is met.
The issue is that TextChanged event is almost perfect, I can get all the text I want BUT the Enter key is ignored on TextChanged and the event is never fired.
So PreviewKeyDown would be the correct one, right? Wrong. PreviewKeyDown only returns the text BEFORE the last key was pressed...and just KeyDown will ignore the Enter key too. Also, KeyUp is not an option as well because I want to be able to block certain keys to be typed.
Is there a event where I can get the whole text of a RichTextBox including the Enter?
Edit:
I am building a TokenizingRichTextBox following pretty much this tutorial, with some minor modifications (I made it into a Blend Behavior instead of a new kind of Control).
The problem is when the user types Enter. Only the text on the last paragraph gets added to the new Token. I would like to user the Enter and the Tab (among other characters) to trigger the Token creation. But I can't, as mentioned before because the Enter is ignored.
Also, although this can be fixed with some Key events, I intent to add some kind of AutoComplete to the RichTextBox. With the AutoComplete none of the Key events will be triggered, just the TextChanged so taking this into account makes things even more complicated.

The TextChanged event is fired, and the newline has already been entered into document at that stage. To get the exact text changed, do something like
var doc = richTextBox.Document;
foreach(var c in evt.Changes.Where(x => x.AddedLength > 1))
{
var change = new TextRange(
doc.ContentStart.GetPositionAtOffset(c.Offset),
doc.ContentStart.GetPositionAtOffset(c.Offset + c.AddedLength));
Debug.WriteLine($"Change: <{change.Text}>");
}

Related

Detect question mark independent from keyboard

The goal is simple: When the user enters chars in a textbox, I want to detect if this char is the question mark key (?).
I don't care what to use (text changed, key down etc...)
One thing to mention: I am working on a german keyboard layout and therefore I need a solution independent from the keyboard (for example: e.Key = Keys.OemQuestion isn't working, it fires when I press the plus (+) key)
Edit: I tried Convert.toString((char)e.Key) which returned \u0095 and e.Key.ToString() which returned OemOpenBrackets
I chose the solution from #HansPassant and managed to do it with the TextInput event.
First in the constructor:
InitializeComponent();
CommandTextBox.AddHandler(TextBox.TextInputEvent, new TextCompositionEventHandler(CommandTextBox_TextInput), true);
You need this code to actually fire the event
in TextInput
if(e.Text == "?")
{
//Do something
}
NOTE:
This does not capture space, control, shift etc.

Real Time Output Of Processed Inputs

Being a beginner in C# I am having problem in a specific implementation. I need to compute two data in real time by which I mean ki the output shows as soon as the inputs are provided with no click of button necessary.
- For example I have a Text Box where if a type a number 5 gets added to it and the output shows in a Label. The label automatically updates when more numbers are typed in real time.
How do I achieve this?
Thanks !
Before explaining the specifics, it's important to point out that from the code's perspective there isn't much difference between clicking a button or responding to the TextBox's event. Here's what I mean.
In addition to calling code procedurally from within your own methods like this:
void MyMethod(argument)
{
...Other Code...
DoSomething(argument);
...Other Code...
}
.Net also allows you to attach method calls to Events. Events are just references to delegates(I'll leave it up to you to research delegates), but they allow you to asynchronously execute your code based on external interaction.
In your question you say that you want to perform a calculation without making the user click a button. Before going into how you'll accomplish that, lets think about what you'd do if there were a button. Chances are you'll drag & drop a button onto the designer surface, then double click it. Behind the scenes you'll suddenly have a method that looks something like this:
void button_ButonClick(object sender, ClickEventArgs args)
{
DoSomething();
}
So you'll go and populate the new method's body with your calculation logic. Under the hood you've actually just had the designer hook that new method up to the Button's click event. So in your case, whether you're adding the calculation logic to a button click or the TextBox's TextChanged event, you're actually doing almost the same thing.
Just for reference, here's the MSDN documentation for TextBox's TextChanged event .
OK I will give it a shot :)
Assume two textboxes and a label on a form.
Each textbox has a text_changed event handler, i.e. if you type something in either text box, the event handler code is called and there you can access the text of each textbox and transform the text into two numbers.
Then you compute the 2 numbers as per your rules and the result is displayed in the label.
This is a very simplified explanation! There must be validation of the inputs in the textboxes to ensure the data format is correct.
Ask more questions if this is not clear enough.

Improve Barcode search in a Textbox C#

In a WinForm C# application I have a Barcode_textbox. In TextChanged event I have an SQL query to check for the TextBox.Text value in the database which is the barcode. The problem is that for each entered digit the SQL Query will be fired, so if a barcode of length 13 it will make 13 check in the database and it is being extremely SLOW.
So, what is the TextBox event that is fired only when the user stops writing in the TextBox (or the barcode reader stpos reading), or what is the optimal solution for checking for a barcode in the database. Note that bacode is of different length
I recall how I did this with success.
I put Timer control in my application with a Interval of a second (1000 milli's). Then I set the Form.KeyPreview property to True.
In the Form Key Press event I store the key strokes. In the Timer.Tick event check if the length of the recorded key strokes exceeds 12 or so characters.
Then fire off the call to SQL, once. When you return a record successfully (or if the textbox contains greater than say 20 chars) clear the stored key strokes.
See update, as at March 2019:
https://stackoverflow.com/a/55411255/495455
Timers are a horrible solution to this.
Use the KeyUp event of the TextBox and check for a carriage return. Most barcode scanners submit a carriage return after the code.. and if they don't do it by default, they come with barcodes to configure it to do so.
You can test this by opening Notepad and scanning barcode after barcode into it. Each one will be on a new line.
Use timer in this fashion that when user stops typing in your textbox for a given small time say 1 second only then get data from database...
Also you can place a check at the characters typed by user with a counter such that when it exceeds that minimum(the minimum size that your key can be) get the data...Will save much time
You could use the Validating event to check the content of the TextBox.
Your user will be required to press the TAB key to change the current focus from the TextBox to the next control following the taborder and the validating event will be triggered
private void textBox_BarCode_Validating(object sender, CancelEventArgs e)
{
// Code to check the barcode on the SQL database....
if(!ValidBarCode(textBox1.Text))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
}
}
Suppose that the next control is the command that executes something using the Barcode inserted (Add)(or a textBox to insert the quantity of the item described by the barcode). After a while all the operation becomes a very natural data entry processing
What about doing the query async?
If you can't or want an easy dirty solution, then I would just stick to the timer

WatiN choosing the correct event string to use with FireEventNoWait for an input textfield

I want to get the input value of an <input type="text"> element, on the fly (while it is being typed) and implement a search method with it as parameter.
I have this piece of code:
_window.Frame(WatiN.Core.Find.ById("a_frame"))
.TextField(WatiN.Core.Find.ById("an_element"))
.FireEventNoWait("event_string", other params);
What event would you think is the best suited for this? I have some thoughts on KeyPressed or KeyUp, but I'd like some other opinions for this matter? I have searched for TextChanged and some similar Event, but I haven't found anything.
Are we to assume the above code isn't working, or? If nothing else works you could always do a do loop right after the text box gets focus, do loop would contain these:
Sleep 100
Doevents
And of course after every 100 ms break and a Doevents, you can check to see if .value has changed, and if so, query your search. When the text box looses focus, you stop the loop.
You are using the webbrowser control, right? And you want to d this using the webbrowser control as opposed to JavaScript? Because, you can get keyup keydown events through the webbrowser controls eventing system, and that would be a better way to do it, but I'm not clear on the who what when where why of what your doing :)

Converting string obtained from database into keypress event

I have a string value in a variable. I want it to be thrown in keypress event.
When user clicks on "Start Writing Button". The text contained in variable gets written to the area whereever cursor has focus.
eg.
string str = "Example"
I have a web page with a textbox and a button. When user clicks on Start Reading button Example gets written on to textbox.
Basically the characters being written should be trapped on
javascript-onKeyPress event
Winform- KeyPress event
etc.
EDIT
I want to use some devices that will be throwing data constantly to my variable using window service. I need to write this data to the active window whereever the cursor has focus currently irrespective of window or web.
I copied data to clipboard and pasted on active window but this is problematic since different tabs are considered to same active window and doesn't writes.
Looking for a proper way rather then workaround I have taken.
Now that you've clarified the question, I suspect you want SendKeys.SendWait.
You'll need to be somewhat careful with it, but it may do what you want.

Categories

Resources