I've spent hours trying to understand what is happening here.
I have a RichEditBox that the user can interact with by tapping on it and using the keyboard or by tapping on a couple of buttons that add some characters inside the RichEditBox.
This is a method I use:
private void ptrPlus_click(object sender, RoutedEventArgs e)
{
try
{
myRichEditBox.Document.Selection.Text = ">";
myRichEditBox.Document.Selection.SetRange(this.Document.Selection.StartPosition + 1, this.Document.Selection.StartPosition + 1);
}
catch
{
//
}
}
What works:
• If I use only the keyboard to write inside the RichEditBox, it works fine
• If I use only the buttons, like this one, it works fine and the characters gets added inside the RichEditBox
What doesn't work:
• If I tap inside the RichEditBox (to either write inside or, or just to make the keyboard appear, and then tap outside it to close it), and then use the button again to add some characters, it works fine for the first two times I press the button.
On the third one, I get a System.AccessViolationException and my app crashes at the
myRichEditBox.Document.Selection.Text = ">";
The app crashes even if that line is inside a try/catch, I don't know why.
I tried to check the state of both the Selection index position and the Selection lenght before and after the RichEditBox got focus as I tapped on it, and it doesn't seem that they change in any way. So I don't really know what is happening here :/
Thanks in advance for your help!
Sergio
EDIT:
I added this handler for the LostFocus event:
void MyRichEditBox_LostFocus(object sender, RoutedEventArgs e)
{
String temp;
int start = this.Document.Selection.StartPosition, end = this.Document.Selection.EndPosition;
this.Document.GetText(TextGetOptions.FormatRtf, out temp);
this.Document.SetText(TextSetOptions.FormatRtf, temp);
this.Document.Selection.SetRange(start, end);
}
This should be rather pointless, but I discovered that it "fixes the error" (even though this shouldn't do anything). The downside is that it adds a new line at the end of the Document, I suspect that's because of the extra \r that the RichEditBox adds by default.
Any ideas on why this handler doesn't let the app crash anymore and/or how to get rid of the extra final \r? Thanks!
EDIT2:
I stopped the debug inside that method and I discovered that the Rtf String didn't contain \r at the end of it, but it had a series of \par that made the RichEditBox add a new line each time.
I tried:
temp = temp.Replace(#"\par", "");
Before the SetSext method, but this just messed up the content of the document, even though it did stop the RichEditBox to add new lines.
I'll if I can find a way to remove those \par without ruining the Rtf content.
Related
I have some software which manipulates text on the Windows clipboard. Specifically it will remove an underscore _ (and return characters) from the front of clipboard text, then check if the remaining text is a URL. If it is, the URL without the underscore is stored on the clipboard, otherwise the original text is left. To monitor the clipboard for changes, I am using code from the answer to this question, provided by DBKK. It works fine, but randomly stops working after an amount of time which can be anywhere between 5 mins and ~24 hours.
Below is the code which is called on the clipboard event trigger:
private void clipboardMonitor_ClipboardChanged(object sender, ClipboardAssist.ClipboardChangedEventArgs e)
{
lock(lockVar)
{
if (locked)
{
return;
}
else
{
locked = true;
//this.clipboardMonitor.ClipboardChanged -= new System.EventHandler<ClipboardAssist.ClipboardChangedEventArgs>(this.clipboardMonitor_ClipboardChanged);
count++;
label1.Text = count.ToString();
removeUnderscore();
//this.clipboardMonitor.ClipboardChanged += new System.EventHandler<ClipboardAssist.ClipboardChangedEventArgs>(this.clipboardMonitor_ClipboardChanged);
locked = false;
}
}
}
I have added various debugging code. Firstly the counter, which made me realise when I write back to the clipboard it triggers the event again. I added the two lines that unset then set the event, so modifying the clipboard doesn't call the event again while it is running. I also added code which would block the event from running if it hadn't finished the previous run (the if(lock) part). Eventually the event stops triggering (as can be seen by a counter not being incremented). It is definitely a problem with the event, I added removeUnderscore() to a button call and that still works fine when the event has stopped triggering.
My theory is that because of the weird way it can call its self, something is going wrong and not adding the event again. I seem unable to lock the the function using a lock object or the boolean value. Any ideas on what might be going wrong?
Edit:
I created another program with the same even which only counts clipboard changes. It appears to run fine indefinitely, so the problem is definitely caused by the event calling it's self. I need a robust way to suspend the even while it is executing.
I am creating a View Controller that records the Phone Number or Email adress of the user, and I want the placeholder of the textfield to change when they select either the "Phone" button, or the "Email" button.
This is just the button that is supposed to change the placeholder
void PhoneSelectBtn(object sender, EventArgs e)
{
EmailPhoneBox.AttributedPlaceholder = new NSAttributedString("Phone");
}
and every time I run the application, it crashes and this is the error that I get:
Objective-C exception thrown. Name: NSUnknownKeyException Reason: [<UIViewController 0x7f813ec3b870> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key EmailPhoneBox.
Native stack trace:
I have tried other options, such as using a segmented control (obviously it is a little different then setting up a button), and I get the same result. I have changed button methods, classes, and the same result occurs every single time. There are no unnecessary events lingering that aren't attached to anything either. Out of ideas. If one could explain step by step what to do, that would be great. I am sure that it isn't a hard thing to do, but I am just learning, and am finding it hard to find applicable documentation on small things like this. Thanks, Josh
It seems that just like with many other Xamarin features which seem like they should be added but aren't, this one needs a custom renderer.
See this link for more.
Another option is
Set the placeholder string to your Editor's Text in Xaml Then in Code behind file:
InitializeComponent();
var placeholder = myEditor.Text;
myEditor.Focused += (sender, e) =>
{
// Set the editor's text empty on focus, only if the place
// holder is present
if (myEditor.Text.Equals(placeholder))
{
myEditor.Text = string.Empty;
// Here You can change the text color of editor as well
// to active text color
}
};
myEditor.Unfocused += (sender, e) =>
{
// Set the editor's text to place holder on unfocus, only if
// there is no data entered in editor
if (string.IsNullOrEmpty(myEditor.Text.Trim()))
{
myEditor.Text = placeholder;
// Here You can change the text color of editor as well
// to dim text color (Text Hint Color)
}
};
I want to disable entering all Emojis (emotion icons) into my input fields in a WPF application. The way I've implemented it is:
txtUserName.PreviewTextInput += LoginPreviewTextInput;
And the LoginPreviewTextInput looks as following:
private void LoginPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!InputValidator.IsValidInput(e.Text))
e.Handled = true;
}
And the IsValidInput of InputValidator looks as following:
public class InputValidator
{
//These characters are allowed in the textbox
private static string pattern = #"^[\w\s,\.\(\)~!#\#\$%\^&\*-=\+\[\]\{\}:;'""<>\?\\|]*$";
public static bool IsValidInput(string previewedInput)
{
var matches = Regex.Matches(previewedInput, pattern);
if (matches.Count == 1)
{
return true;
}
return false;
}
}
The strange part is that it works for all Emoji icons in the virtual keyboard, except the Happy Emoji.
It does not work, because LoginPreviewTextInput is not invoked once I enter this Emoji in the Windows Virtual Keyboard (it works for all the other Emojis).
The Happy Emoji is the one shown in the following picture:
When the happy emoji is entered into the textbox ,the textbox looks as follows:
The happy emoji has been entered into the textbox. You can see that there is even a Watermark that is displayed when text propery of a textbox is empty.
When I look at the text property of the textbox in snoop, It is indeed empty, and the bounded property is the viewmodel is empty (the setter has never been invoked).
Again, happens only for this specific emoji (the happy one). All other Emoji get to the LoginPreviewTextInput method, do not match the regex and are ignored.
After spending some time looking into the problem I have come to a solution to this problem.
Why can you you press the Happy Emoji?
The reason that you're able to enter the happy emoji into your application from the virtual keyboard is because it's one of the default windows symbols / has an actual character attached to it. (something along those lines).
Although other emojis can display as such I believe it the default behaviour of the virtual keyboard to just use those symbols as they're already available and don't need a variety of characters to create.
This also happens with a lot of other emoji's such as stars and hearts.
This is what's shown when you press "Happy face":
This is what's shown when you press "Love eyes face":
As you can see what's actually happening is that all the other emoji's are being flagged for that backslash that is in front of them.
How can you solve your problem?
A solution to your problem could be for the regex to check that the code matches a set criteria. For example, that all characters are [a-Z] or whatever you want it to be. this is most likely the better way to fix your problem as it means you're not creating a massive exclusion list.
I have an application that allows users to browse through data. I have menu items controlling navigation and a RichTextBox displaying the data. Very straightforward.
tl;dr version
It mostly works except for one strange problem. There are instances where the RichTextControl will replace the first character typed with a random unicode character. Feel free to download this sample app and see for yourself:
http://www.technitivity.com/stackoverflow/RichTextFocusTest.zip
Full Explanation
The issue happens when navigating between rows. It's best described with a few use cases:
Use Case 1
Navigate anywhere into the dataset.
Press back.
Press next.
Type any letter, say, "F".
Result: "F" appears in the RichTextBox as expected.
Use Case 2
Navigate anywhere into the dataset.
Press back twice.
Press next twice.
Type the letter "F".
Result: instead of "F", "ᅲ" appears in the RichTextBox.
Use Case 3
Navigate anywhere into the dataset.
Press next twice.
Press back twice.
Type the letter "F".
Result: instead of "F", "᧴" appears in the RichTextBox.
The navigation process entails nothing more than:
// either forward
i++;
// or backward
i--;
// then update
RichTextBox1.Text = MyData[i];
Procedurally speaking:
// This works
RichTextBox1.Text = MyData[3];
// This works
RichTextBox1.Text = MyData[3];
RichTextBox1.Text = MyData[2];
RichTextBox1.Text = MyData[3];
// This doesn't work
RichTextBox1.Text = MyData[3];
RichTextBox1.Text = MyData[2];
RichTextBox1.Text = MyData[1];
RichTextBox1.Text = MyData[2];
RichTextBox1.Text = MyData[3];
Granted, that's not what's actually happening, but it is what's effectively happening.
It's important to note that this doesn't happen if the RichTextBox loses focus between updates. It only happens if the RichTextBox retains focus while its Text attribute is updated in accordance with the above description.
I'm at a complete loss about what's causing this, how to fix it, or why I can't seem to find anyone else with this problem.
I've reproduced it on 64-bit Windows 7 and 32-bit Windows Vista. This is on .NET Framework 4 though I was also able to reproduce on a .NET Framework 2 project.
Here's hoping someone else has run across this (and solved it!)
Edit:
Here's a screenshot:
http://www.technitivity.com/stackoverflow/RichTextBox-Screenshot1.png
As mentioned in the comments, to reproduce this in the sample app, you have to use the keyboard menu shortcuts. If you click on the menu items (or the toolbar buttons), the RichTextBox loses focus and the problem goes away. But if you navigate through the items using Alt+Left or Alt+Right (back/next) and then type, you should see something like what's shown in the above screenshot.
I hesitate to call this an "answer", but I couldn't find a "Post a Hack" button and this hack does get me by for now. I'm not thrilled about it, but sometimes you just have to move on. Here it is.
Since the problem went away when the RichTextBox lost focus, I tried an experiment:
I created a visible, 0-pixel wide textbox, called Hacktastic.
I added a KeyPress event to the RichTextBox.
On KeyPress:
Hacktastic.Focus();
Hacktastic.Text = KeyChar.ToString();
MyRichTextBox.Focus();
This worked and (at least for now) I'm sticking with this as a solution. If anyone could still try out my sample project and reproduce and/or solve this, I would love further feedback:
http://www.technitivity.com/stackoverflow/RichTextFocusTest.zip
Steps to repro in the test project:
Using Alt+Right arrow, move through the dataset to, say, the fourth record.
Using Alt+Left arrow, move back through the dataset two places, to the second record.
Using Alt+Right arrow, move back to the fourth record.
Press any KeyChar.
Observe KeyChar is replaced with a "random", large-value unicode character.
I say "random" because a specific set of navigation (back/next) keystrokes will insert the exact same unicode character. However, depending on where you start in the set or how far back you go, you'll get a different character.
Also, note that only going back one record and forward one record does not cause the problem. You have to move at least two records for this to happen.
I have a RichTextBox onto which I write long lists of data using a simple write method (see down)
I use vertical scrolbar, and writing and clearing is fine.
The problem is with new text after clearing the text.
I use textbox.clear(); which clears the box OK, but when new text arrives, the old (cleared!) text shows up again, followed by the new text.
I have also tried:
ResetText, Refresh, Update. dispose, Text =" , richTextBox.Document.Blocks.Clear(); (dont have that one).
Have also tried new textbox = new textbox, all for no avail.
The text shows again and again, until I reset the application.
I have seen several form threads on that one, but non helped.
My guess: I use both scroll bars. A scrollbar must have a buffer, The data is kept somewhere in the active scrollbar buffer?
Any (good) idea will be blessed.
This is how I write / erase the text in the richtextbox:
(simplified. mainDisplay is a RichTextBox)
public void mainDisplayText(string text)
{
this.mainDisplay.AppendText(text);
this.mainDisplay.ScrollToCaret();
}
private void btnClear_Click(object sender, EventArgs e)
{
//Have tried all these options:
this.mainDisplay.Text = ""; //or
this.mainDisplay.Clear(); //or
this.mainDisplay.SelectAll(); //or
this.mainDisplay.SelectedText = "";
}
You're reusing the same string, so:
this.mainDisplay.Clear();
text = string.Empty;
Should do the trick :)
Strange indeed. Could this be some issue in .net 4.7.x ? Since last week I compile everything in 4.7.2 and this problem has surfaced here also. Clear() seems to bring back the .Text content. So a Clear() after Text="" does not work.