Simulate Keyboard events on WPF Textbox - wpf

I am have textbox and 4 button in my page (A, B, Delete and Enter). If i click the button it has to send key event to the textbox.
Problem:
No action is happening on the textbox.
Code:
void buttonElement_Click(object sender, RoutedEventArgs e)
{
// create variable for holding string
String sendString = "";
// stop all event handling
e.Handled = true;
// set sendstring to key
sendString = ((Button)sender).CommandParameter.ToString();
// if something to send
if (!String.IsNullOrEmpty(sendString))
{
// if sending a string
if (sendString.Length > 1)
{
// add {}
sendString = "{" + sendString + "}";
}
// set keyboard focus
System.Windows.Input.Keyboard.Focus(this.txtSearch);
System.Windows.Forms.SendKeys.SendWait(sendString);
}
}
Geetha.

Daniel Rose is right. Wouldn't it be easier this way?
You take the Text property of the textbox and on the buttonclick you append the right character to this string of when the delete-button is pressed just erase the last character of this string.

Why are you trying to send a key event to the TextBox, instead of setting its Text property?

Related

I want to stack buttons with the same name but be able to call them as individuals

I want to declare one button as so: private: System::Windows::Forms::Button^ NewButton; and then make 11 of the same button like this:
int Loc=0;
for(int i=1;i<12;i++)
{
this->NewButton = (gcnew System::Windows::Forms::Button());
this->NewButton->BackColor = System::Drawing::Color::White;
this->NewButton->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->TheList->Controls->Add(this->NewButton);
this->NewButton->Location = System::Drawing::Point(-1,Loc-1);
this->NewButton->Size = System::Drawing::Size(200, 30);
this->NewButton->TabIndex = i;
this->NewButton->Text = L"hej"+i;
this->NewButton->Name = L"Button"+i;
this->NewButton->Click += gcnew System::EventHandler(this, &Form2::NewButton_Click);
Loc+=29;
}
private: System::Void NewButton_Click(System::Object^ sender, System::EventArgs^ e) {
NewButton->Text = "Hello";
}
it does now not matter switch button i press to start the event but only the last button made changes it's text. is there a way to have the buttons called by maybe a number or it's name ? if not please give alternative solutions.
NewButton is an instance variable, so on each iteration of your loop you replace it with a different instance - only one can be saved, so that is the last one.
In the button callback when it's pressed you get sender as a parameter which should be the button that was pressed. So, you should use sender to update the text on the button rather than using NewButton.

how to use textChanged event when from barcode reader

I am using a Barcode reader to get bar code from products .
i get the code in a textfield . and i put textchanged event on that textbox .
but the problem is that when bar code puts it value ( for example if bar code is 5 digit ) then textchanged event is fired five times .
how to get ride of this thing ???
You should be able to program your Barcode reader to output a prefix character and a suffix character (one output before the scanned value and one afterwards). Let's say that you set it up to output an asterisk (*) before the scanned data value and output a carriage return (CR) afterwards. Attach a handler to the TextBox.PreviewTextInput Event and listen out for the asterisk character:
private void PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == "*")
{
e.Handled = true;
// Data input has started
}
}
You can use this to pop up a message saying 'Scanning...', or anything else that you require. Next, attach a handler to the TextBox.KeyUp Event and listen out for the Enter key:
private void KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
string scannedValue = ScanTextBox.Text.Replace("*", string.Empty);
// Do something with scannedValue
}
}
Now the scannedValue variable should contain the scanned barcode value.

Detect when caret position changes in RichTextBox

I am trying to implement very simple text formatting functionality for a RichTextBox in WPF. This just consists of a few bold, italic, etc ToggleButtons just above the RichTextBox. See image below, but ignore the top TextBox - the RichTextBox is the bigger one at the bottom.
Toggling formatting for either a selection or at the caret position (for text that will be typed in) is not a problem, as I'm doing this:
private void BoldButton_Checked(object sender, RoutedEventArgs e)
{
this.SetSelectionBold(true);
}
private void BoldButton_Unchecked(object sender, RoutedEventArgs e)
{
this.SetSelectionBold(false);
}
private void SetSelectionBold(bool isBold)
{
var selection = this.RichText.Selection;
if (selection != null)
{
selection.ApplyPropertyValue(TextElement.FontWeightProperty, isBold ? FontWeights.Bold : FontWeights.Normal);
}
}
However, if the user moves the caret somewhere else (e.g. from bold text to normal text) then I'd like the ToggleButtons to reflect that state, in much the same way as it works in Word. Is it possible to detect when the caret position changes, and take action accordingly?
Hook yourself into SelectionChanged event and get current caret position, and test if the property exists on that selection?
In the event, probably you want something like:
var selection = richTextBox.Selection;
if(selection != null)
{
if(selection.GetPropertyValue(TextElement.FontWeightProperty) == FontWeights.Bold)
// todo; enable your button
}
If that event is not triggered by caret positioning(the document doesn't say anything about that),
you probably need to inherit from RichTextBox and override OnSelectionChanged, after that you need to actually generate your own Caret, eg:
var currentCaretPlusOne = new TextRange(richTextBox.CaretPosition,
richTextBox.CaretPosition+1);
if(currentCaretPlusOne != null)
{
if(currentCaretPlusOne.GetPropertyValue(TextElement.FontWeightProperty)
== FontWeights.Bold)
// todo; enable your button
}

how can I know if backspace or delete was pressed in TextChanged event of textbox

I use the TextChanged event of a textbox.
for instance I have the text in the textbox:
"a b"- 2 spaces between a,b
I go in the middle of the 2 spaces, and hit backspace. I can not check by comparing the new text with the old which key was pressed (if backspace or delete was pressed, the newtext is the
same "a b"-1 space between letters.
How can I check which key was pressed?
Why do you care? If you're handling the TextChanged event, you're not supposed to care what about the text was changed, just the fact that it was.
If you need to care about what specifically was changed, you need to handle a lower-level event, like KeyDown:
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Back || e.Key == Key.Delete)
{
// The user deleted a character
}
}
I know this is an old question, but maybe someone will find this helpful.
I used an integer, that counts length of current characters. It updates with the event.
Every time, the event is triggered, I check, if the length of the counter is longer than the current length of the text. If it is, we know, there was something deleted.
private int counter = 0;
private void TextChangedEvent(object sender, TextChangedEventArgs e){
if(counter > textbox.text){
counter = text.Length;
//deleted
}
else{
counter = text.Length;
//added}

RichTextBox and Inserting at Caret Positions

Here is the deal: I have a RichTextBox control and it works fine. The problem is that there is a button "Insert Current DateTime" which adds/injects the current datetime into the RichTextBox. The user can enter the datetime anywhere where the caret is pointing. This involves complicated string manipulation and stuff.
Any ideas how to get the current caret position. Whenever I get RichTextBox.CaretPositon it seems it is pointing to the start of the RichTextBox and not where the actual caret is.
UPDATE 1:
The date time button click code:
private void DateTimeStampButton_Click(object sender, RoutedEventArgs e)
{
//TextRange tr = new TextRange(textBox.Selection.Start, textBox.Selection.End);
var tr = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);
if(tr.Text.Length == 2)
{
if(tr.Text == "\r\n")
{
tr.Text = tr.Text.TrimStart(new[] { '\r', '\n' });
}
}
textBox.CaretPosition.InsertTextInRun(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": ");
DateTimeStampButton.Focusable = false;
}
private void SharpRichTextBox_LostFocus(object sender, RoutedEventArgs e)
{
SetValue(TextProperty, Text);
var binding = BindingOperations.GetBinding(this, TextProperty);
if (binding == null) return;
if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default || binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
{
// if (TextProperty != null) BindingOperations.GetBindingExpression(this, TextProperty).UpdateSource();
}
}
public string Text
{
get
{
var newValue = new TextRange(Document.ContentStart, Document.ContentEnd).Text.RemoveNewLineAndReturn();
return newValue;
}
set
{
if (!String.IsNullOrEmpty(value))
{
SetValue(TextProperty, value.RemoveNewLineAndReturn());
Document.Blocks.Clear();
Document.Blocks.Add(new Paragraph(new Run(value)));
OnPropertyChanged("Text");
}
}
}
UPDATE 2:
Turned out the problem was with the DateTime button being Focusable. I turned it to be not focusable and it worked as expected. When focus was lost on the RichTextBox it was resetting the caret position. It happened only once since in the code the btn_DateTime was dynamically being set as Focusable = false. I placed Focusable = false in XAML and everything worked fine from the start.
I'm using this code to successfully do what you are attempting:
private void insertNowButton_Click(object sender, RoutedEventArgs e)
{
//NOTE: The caret position does not change.
richTextBox1.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
}
EDIT: Addressing Update 1
private void DateTimeStampButton_Click(object sender, RoutedEventArgs e)
{
var tr = new TextRange(textBox.Document.ContentStart, textBox.Document.ContentEnd);
if (tr.Text.Length == 2)
{
if (tr.Text == "\r\n")
{
tr.Text = tr.Text.TrimStart(new[] { '\r', '\n' });
}
}
/* Changing the text is the only way I can get the date to insert at the beginning */
tr.Text = "I need a beer at ";
textBox.CaretPosition.InsertTextInRun(DateTime.Now.ToString());
}
It looks like SetValue is changing the text so based on my test that actually changing the text resets the caret, I would agree with you that SetValue is causing the problem...
I tried this solution with WPFToolkit.Extended RichTextBox and it didn't work for me.
However I found another one and thought it would be good to post it in here in case someone else could use it.
My problem was also that the after I clicked a button that is supposed to append text at the caret location, it instead adds it at the beginning of the RichTextBox.
So The solution I found is similar to the one in here -
RichTextBox CaretPosition physical location
Instead of using CaretPosition I used RichTextBox.Selection.Start.InsertTextInRun("SomeText").
It considered the selection's start as the caret position even though no selection was made and therefore was good enough for me.
I hope someone will find this useful :)
This worked for me:
private void InsertText(String text, RichTextBox rtb)
{
rtb.CaretPosition = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
rtb.CaretPosition.InsertTextInRun(text);
}
I found the code here:
How do I move the caret a certain number of positions in a WPF RichTextBox?

Resources