How to use 0x08 - c#

How do you use the ASCII value of backspace 0x08 programmatically in a WinForms TextArea? I tried in a console program:
Console.WriteLine("Hello" + (char)0x8 + "World");
And it shows as I expected:
HellWorld
Where as I tried in a WinForms TextArea to fill the value:
txt.Text += "Hello" + (char)0x8 + "World";
It shows like this:
What to make backspace event to trigger other than using Keyboard's event to make the display as I expect by using the value of 0x8 alone not accessing with any text field events. Through programmatically to print "HellWorld" in text field.

Characters and keypress are not related directly. You would have to get a Backspace keypress into the textbox in order to erase a character.

If you want to simulate someone typing in the textbox, then you might do so using SendKeys.Send(), e.g:
txt.Select();
SendKeys.Send("hello");
SendKeys.Send(((char)0x8).ToString()); // send backspace using 0x08
SendKeys.Send("{BS}"); // send backspace using predefined code
SendKeys.Send("world");
But pre-processing the strings seems much simpler (and safer), e.g:
var str = "hello";
txt.Text += str.Substring(0, str.Length-1);
Note: SendKeys.Send sends keystrokes to the active window. So if another window gets the focus while the above code is running, then the keystrokes might end in a different window.

The backspace character was introduced for thin clients that send input to a server character by character, to allow end users to fix a typo that was already sent. Modern applications usually have no use for such a character, as client applications now usually just wait until the user has finished entering data before sending it to the server.
That is why the TextBox control does not have support for it, and probably why people are wondering why you need this.
Anyway, you'll need to pre-process the data yourself before setting the TextBox's Text. You could for instance use regular expressions to simulate this behavior.

Related

How to PgUp/PgDn with SendKeys to a foreground textbox

I am trying to page up/down the contents of a simple textbox control in a simple Windows Form on NET 6.0, but something is wrong. Textbox shortcuts are enabled (probably why SendKeys.SendWait("^a"); works) and readonly is false.
I have a method (not on the UI thread) that I call to SendKeys.SendWait("{PgUp}"); to the foreground app (which is both the key sender and textbox (with focus) receiver.
If I type PgUp on the keyboard, the textbox pages up as expected.
If I SendKeys.SendWait("^a");, the textbox selects all text as expected.
If I Sendkeys.SendWait("{PgUp}");, the textbox adds a blank line to the bottom of the text.
From this I conclude that my code is working because it sends "^a" and the textbox receives it and selects all text. But somehow the textbox does not handle the "{PgUp}" key, even though it does when the PgUp key is sent by the keyboard.
I've read easily a dozen articles and posts on the web and SO that talk about paging using scrolling events, positioning the caret and then scrolling to the caret, and so on. But none of them say anything about why SendKeys(^a) and keyboard PgUp would work but SendKeys.SendWait("{PgUp}") would fail.
Can anyone tell me what I'm doing wrong and maybe what I need to do (or read) to fix it? Thank you
UPDATE: Jimi asked for some code, so here is the code that I use to send the ^a and the {PgUp} keys. I know this is not on the UI thread because it is executed from a voice-driven recognizer thread. The app is a voice-driven app that displays content in the textbox by textbox.AppendLines calls. I was trying to PgUp and PgDn the multi-line textbox by voice as well.
When I tried to use Send (I normally use .SendWait for everything in other programs), I received the following error message:
System.InvalidOperationException: 'SendKeys cannot run inside this
application because the application is not handling Windows messages.
Either change the application to handle messages, or use the
SendKeys.SendWait method.'
It is true that my app does not intercept Windows messages. I can't figure out why the app can receive and properly process my keyboard keys, and my "^a' shortcut keys, but not the SendWait("{PgUp}") key.
internal static void
HelperPageUp() {
var keys = "{PgUp}";
keys = "^a";
SendKeys.SendWait(keys);
}
I'm starting to think that {PgUp} is never handled by a textbox or control. Instead, probably {PgUp} must be handled by logic in a case statement that converts PgUp "orders" into sets of actions that implement whatever PgUp means to the app that receives the PgUp key. So maybe I will have to add a keystroke handler to the form. Maybe something like this:
textBox1_KeyUp(object sender, KeyEventArgs e) {
// identify the special key and implement what it means
if (e.KeyCode == Keys.PageDown) {
...
e.Handled = true;
}
Yes, my thought at the end of the question was correct. The ^a was handled by the textbox because I had textbox.EnableShortcuts=true;, so the textbox handled the popular ^a shortcut. But keys like {PgUp} are a different matter; they are not included in shortcuts.
The solution was to write code to handle the {PgUp} key explicitly in the form. Here is my code that worked.
void
textBox1_KeyUp(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.PageUp) {
// page the viewport up; watch for end of content
var charIndex = textBox1.SelectionStart;
var lineIndex = textBox1.GetLineFromCharIndex(charIndex);
// move 20 lines up, but not past zero
var newLine = lineIndex - 20;
var newIndex = Math.Max(0, newLine);
// set the new anchor and scroll to it
var newAnchor = textBox1.GetFirstCharIndexFromLine(newIndex);
textBox1.Select(newAnchor,0);
textBox1.ScrollToCaret();
e.Handled = true;
}

Why is a C# console processing multiline paste as Enter key presses?

I have a C# application which handles key presses and will break the loop when the Enter key is pressed. The problem I am encountering is that when a multiline paste event occurs, the console is interpreting the newlines as Enter key presses.
Example that doesn't cause Enter keypress:
select something \n from somewhere \n where condition
Example that does cause Enter keypress:
select something
from somewhere
where condition
Does anyone know why this would be? And is there any way to stop this without digging into the WndProc stuff for intercepting a Paste event?
On Windows, new lines are \r\n. When you press the Enter key, these two characters are input. So if you put a \r before each of your \n they should be treated as newlines.
Hi it looks like someone used Console.ReadLine() to trigger loop break.
https://msdn.microsoft.com/pl-pl/library/system.console.readline(v=vs.110).aspx
Effectively loop breaks when you start new line not only press enter Key.
The Enter key press can't be resolved back into \r\n as far as I can tell, so I don't think we can process based on those characters - but I was able to get a hint (for my situation anyway) if the user was pasting multiline text by interrogating Console.KeyAvailable.
So now, I look to see if (Key == ConsoleKey.Enter && Console.KeyAvailable == false) to determine whether to process it as "genuine" Enter key press or not (as there usually aren't keys available in my situation when Enter is pressed).
See this commit for more info

Partially read-only textbox in c#

I've got a list of illegal positions and characters that can't move from those positions. How would I prevent those from being modified in the TextChanged event? Every solution I've come up with has been extremely hacky and unreliable, or has relied on the KeyDown event, which doesn't prevent the user from deleting the read-only text in other ways (select the text and delete it, or just press the backspace key).
I've thought of doing something like this:
//CharPos is a class with an int (CharPos.Position) and a char that
//should be at that int's position (CharPos.Ch)
foreach (CharPos p in IllegalPositions)
{
console.Text = console.Text.Remove(p.Position, 1);
console.Text = console.Text.Insert(p.Position, p.Ch.ToString());
}
But it completely messes up and goes on an infinite loop. And even if I stopped it from doing that, it wouldn't work if you changed the character count of the text, by using the delete key for example. Maybe I could use regex somehow? (I dunno, I have no experience at all with regex).
Can you combine multiple TextBoxes (for editable parts) with TextBlocks (for readonly parts)? You would just need to play with styling of the two to match
Could you please check the link below:
Disabling or making it readonly a part of the values in a Text Box (.net)
rtBox.Select(0, (rtBox.Text = "I am fixed content").Length);
rtBox.SelectionProtected = true;
rtBox.AppendText(Environment.NewLine);

Is there a way to append output to a text field without taking focus?

I'm trying to add text to a RichTextBox using the AppendText method, and would like to find a way to Not take focus of the text box in this motion - reason being that I have an event response to the text box getting focus, that causes a conflict in my overall scheme...
Again, the question here is effectively; How can I use the AppendText method without triggering focus on a rich text box.
As I'm typing this I've almost decided that I can remove my event response method before the append and add it in again after; but if anyone has a better suggestion I'm all ears.
Thanks. And if I can submit any code to spur suggestions I'm open to it; I just assume that most anyone using this site can visualize what I'm portraying.
You can use a boolean variable to determine if it was you who fired the event (or the user)
bool firedByUser ;
When calling the AppendText method do something like this
firedByUser = false ;
rtb.AppendText("sample") ;
firedByUser = true ;
And in the method that you are handling the Focus on the RichTextBox
if(firedByUser)
{
//keep doing what you are doing now
}

Monitoring text property validity as user types

[Winforms Application .NET 4.0 C#]
I have a textbox that receives data from a handheld barcode scanner.
I want my application to check if the text is valid without the user having to do anything.
Example rule:
Text length =18 and starts with '1520'
Text length =17 and starts with '0520'
Should i checkit with:
TextChanged event?
Add a timer to check the rules every 200-300ms?
something else?
TextChanged event will suffice, I have implemented something similar in the past and you will only be notified once so you will have the full barcode on each scan.

Categories