This question already has answers here:
Masked TextBox Input Align Left
(2 answers)
Closed 9 years ago.
I'm writing an app in C# with Visual Studio 2012, and I'm needing to format some input text using MaskedTextBox. The user will type in a folder path to the text box, but since the folder path is relative to another path, I need it to start with ".\", but I do not care how long the path is.
Right now, I have the mask set for the box to \.\\CCCCCCCCCCCCCCCCCC. This works fine except for the fact that when the user clicks into the box, it places the cursor where they click instead of the beginning of the box.
Is there a way to set the mask to still put in the ".\" but not to set any limit on the characters that come after it?
Or is there a way I'm overlooking?
EDIT: More info
So I've tried a couple recommended things, but they don't seem to work. The answer linked here doesn't work well. While I can set it to go to that selection point when I click on the box, it will go there every time you need to click on the box. So you can't select the whole box or edit part of what you typed, which is even worse for usability.
I also tried the method suggested by Adelmo. I made an even handler like so:
public Form1()
{
InitializeComponent();
refreshList();
this.textBoxPrintFolder.GotFocus += new EventHandler(textBoxPrintFolder_GotFocus);
}
private void textBoxPrintFolder_GotFocus(object sender, EventArgs e)
{
this.textBoxPrintFolder.Select(2, 0);
}
This works when tabbing to the box, but apparently clicking on the box doesn't go into the GotFocus event.
I've also tried using the MouseEnter event. While it does work, it takes a few seconds before it will move. Not ideal.
Any help would be greatly appreciated.
Maybe using onFocus event:
You can control cursor position (and selection) by TextBox.SelectionStart and TextBox.SelectionLength properties.
Example if you want move cursor to before 3th character set SelectionStart = 2 and SelectionLength = 0.
http://social.msdn.microsoft.com/Forums/en-US/04362a62-8cbf-4d86-a1bc-2aba8e4978ca/cursor-position-in-textbox
Hope it help you
Related
Long time listener, first time caller here. I'm having a strange issue with the TextBox in WinRT C#/XAML that I hope someone may be able to help me with.
Basically, I'm working on creating a Custom Control that essentially requires a second TextBox to be a copy of the first, including showing the same Text, and showing the same Selected Text. Obviously for the Text requirement I simply respond to the TextChanged event on the first TextBox and set the Text of the second TextBox to the Text from the first, which works great.
For the Selected Text requirement I started with a similar solution, and my code for this is as follows:
void TextBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
this.TextBox2.Select(this.TextBox1.SelectionStart, this.TextBox1.SelectionLength);
}
This seemed to work pretty well when initially used with a mouse:
But I'm having a problem when selecting text with Touch. I double-tap within the TextBox to create the first "anchor" as you do in Touch, then drag to begin the selection; but I only ever manage to select a single character normally before the selection stops. The TextBox doesn't lose focus exactly, but the behaviour is similar to that; the selection anchors disappear and I can't continue selecting anything unless I re-double-tap to start a new selection. If I remove the code to select text in TextBox2 then the Touch selection behaves perfectly in TextBox1.
I've been trying to fix this for a while and cannot, I'm not sure if I can get the desired behaviour with WinRT TextBoxes. Does anyone have any ideas? Or perhaps another way to implement a solution with two TextBoxes with this behaviour?
Thanks a lot.
So this is far from an answer, but discovered a few things that maybe will help you or others come up with a potential workaround. Apologies if these are things you've already seen and noted.
First, it's not the call to TextBox2.Select() that's the problem per se. This for instance, works fine for me
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
TextBox2.Select(3, 5);
}
unfortunately, using start and length versus the hard-coded 3 and 5, that is, the following, DOES NOT WORK:
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
TextBox2.Select(start, length);
}
I also discovered that I could select TWO characters if I started from the end, but only one from the beginning. That got me to thinking about dispatching the call to set the second selection:
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low,
() => TextBox2.Select(start, length));
}
Now I can select 2 from the front and 3 and sometimes 4 from the back. Took it a step further, and was able to select as many as six or seven with a really fast swipe.
private void txt1_SelectionChanged(object sender, RoutedEventArgs e)
{
var start = TextBox1.SelectionStart;
var length = TextBox1.SelectionLength;
Dispatcher.RunIdleAsync((v) => Highlight());
}
public void Highlight()
{
TextBox2.Select(TextBox1.SelectionStart, TextBox1.SelectionLength);
}
Seems like the trick to working around this is not setting TextBox2 until whatever vestiges of the TextBox1 SelectionChanged event have completed.
This may be worth registering on Connect.
Mine is only a partial solution as well.
I did some debugging and noticed that the SelectionChanged event is fired throughout the text selection process. In other words, a single finger "swipe" will generate multiple SelectionChanged events.
As you found out, calling TextBox.Select during a text selection gesture affects the gesture itself. Windows seems to stop the gesture after the programmatic text selection.
My workaround is to delay as long as possible calling the TextBox.Select method. This does work well, except for one edge case. Where this method fails is in the following scenario:
The user begins a select gesture, say selecting x characters. The user, without taking their finger off the screen, pauses for a second or two. The user then attempts to select more characters.
My solution does not handle the last bit in the above paragraph. The touch selection after the pause does not actually select anything because my code will have called the TextBox.Select method.
Here is the actual code. As I mentioned above, there are multiple selection changed events fired during a single selection gesture. My code uses a timer along with a counter to only do the programmatic selection when there are no longer any pending touch generated selection changed events.
int _selectCounter = 0;
const int SELECT_TIMER_LENGTH = 500;
async private void TextBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
// _selectCounter is the number of selection changed events that have fired.
// If you are really paranoid, you will want to make sure that if
// _selectCounter reaches MAX_INT, that you reset it to zero.
int mySelectCount = ++_selectCounter;
// start the timer and wait for it to finish
await Task.Delay(SELECT_TIMER_LENGTH);
// If equal (mySelectCount == _selectCounter),
// this means that NO select change events have fired
// during the delay call above. We only do the
// programmatic selection when this is the case.
// Feel free to adjust SELECT_TIMER_LENGTH to suit your needs.
if (mySelectCount == _selectCounter)
{
this.TextBox2.Select(this.TextBox1.SelectionStart, this.TextBox1.SelectionLength);
}
}
Before I've performed adding this question I've searched in this site for my question - According to website's posting rules - and I found these links and it didn't help me:
Get word under mouse pointer
get the text under the mouse pointer
Getting the text under the mouse pointer
My questions is:
I'm programming a Geology dictionary and it is available for users now, but I want to add a feature that make users see the translation of a specific word when they move their mouse on it for a specific period and the word may be in any app like MS Word,IE,Firefox or any other app (I quoted this idea from the Easy Lingo dictionary if you know it), then the application will perform a query in the database and return the result to the user in a tooltip or something like that at the position of the mouse.
So, how can I get the word under the mouse pointer, is that an API or what?
Would you help me please?
Almost every visual control (like textboxes or labels) has the MouseHover-event.
private void label1_MouseHover(object sender, EventArgs e)
{
// get text by mouse-over
string textOfTheLabel = ((Label) sender).Text;
string translatedText = GetTranslationFromDB(textOfTheLabel);
// tooltip
System.Windows.Forms.ToolTip toolTip1 = new System.Windows.Forms.ToolTip();
toolTip1.SetToolTip((Label) sender, translatedText);
}
I have two textbox's. I have an event setup for the "onLostFocus" of the textbox's. If i finish typing a word into both boxes one after the other all is well. At the point where i click back on the first textbox i want to click halfway through the word (perfectly resonable thing for a user to do). When the onLostFocus event fires here is my code :
void tbox_LostFocus(object sender, RoutedEventArgs e)
{
IInputElement focusedelement = FocusManager.GetFocusedElement(this);
if (focusedelement is TextBox)
{
TextBox focusedTextBox = focusedelement as TextBox;
int focusIndex = m_commandsStacker.Children.IndexOf(focusedTextBox);
int caretIndex = focusedTextBox.CaretIndex;
The caret index returns as 0 when i call focusedTextBox.CaretIndex. At that point I need to refresh the whole form and set parameters and all other kinds of whizzery, storing the texbox index and caret position to put everything back the same. Why does it return 0 and not the position where the caret should be halfway between the word?
This just doesn't work in c# express edition 2008 (whatever version of WPF that is) so the best thing to do here is to switch to onTextChanged and run the exact same code there, which works a treat. Its obviously annoying that you have to run the code multiple more times than if it worked on lost focus. When I get the time I will check if it works in c# express 2010 as we are upgrading (eventually)
I recently started getting acquainted with Visual Studio 2010 and C# for an internship. C# doesn't include a built-in InputBox function, so I made my own form, with a text box, two buttons and a simple label.
I have a function set up to allow the programmer to call the form in regular format (where the user enters input via the textbox) or yes/no format (where the form just displays a question and the yes and no buttons).
When I switch over to yes/no format, I want to center the label programmatically. I've been using the code:
labelNote.Left = inputBox.Left + (inputBox.Width / 2) - (labelNote.Width / 2);
This should put the center of the note in the center of the form. However, if the contents of the label change (making the new label longer or shorter) the properties don't update to reflect the new size. It won't center unless it includes the original text. Is there some way to force an update? I foresee this becoming a problem with positioning objects for scalability in the future.
Thank you for your time
I'm assuming you have the sizing within an actionlistener. Specifically the forms' resize action listener. Then whenever the form is resized it is called and all of you code is recalled. Then to force an update from somewhere else you just have to call the actionlistener.
Actionlistener:
Private Sub formName_Resize(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Resize
Calls actionlistener:
formName_Resize(sender, e)
Well, you could attach an event to Label.TextChanged. Frankly it would be better to change the TextAlign or something like that though: try to perform the layout in a declarative fashion instead of doing it explicitly through code. That tends to make things work rather better.
I've found the [TableLayoutPanel]1 control to be reasonably easy to work with - most of the time (and occasionally a complete pain).
It turns out that I made a stupid mistake (a common theme for me in debugging. The really small stuff goes unnoticed for the longest amount of time).
The label resizing was not the issue. The issue was the order in which I changed the contents of the label and then called the function to calculate its new location. I was calling the location calculation first, so it found where to center the label based on the old contents. I didn't notice for so long, because the text was changing properly. I took it for granted that the functions were being called in the correct order.
So, when it doubt, check the order in which you're writing your code. Thanks for you help anyway, everyone. I ended up finding out some neat things that could be applicable to other scenarios (such as the MeasureString function in the Graphics class).
I'm coding a simple text editor using Windows Forms. As in many editors, when the text changes the title bar displays an asterisk next to the title, showing that there is unsaved work. When the user saves, this goes away.
However, there is a problem. This is handled in the change event of the main text box. But this gets called too when a file is opened or the user selects "New file", so that if you open the editor and then open a file, the program says that there are unsaved changes. What is a possible solution?
I thought of having a global variable that says whether the text changed in a way that shouldn't trigger the asterisk, but there has to be a better way.
before loading data to a textbox, unassociate first the eventhandler for change
uxName.TextChanged -= uxName_TextChanged;
uxName.Text = File.ReadAllText("something.txt");
uxName.TextChanged += uxName_TextChanged;
This is a horrible solution, but every time the text change event fires, compare the value of the textbox to some variable, and if they are different store the contents on the textbox in a variable and add the asterisk. When the method is invoked via the New File dialog or any other such event that is NOT changing the text, the asterisk won't appear.
This is not a viable solution for a real text editor since the memory would quickly get out of hand on even medium-sized files. Using a finger tree or whatever data structure text editors use to compare "versions" of the text is the only real efficient solution, but the premise is the same.
http://scienceblogs.com/goodmath/2009/05/finally_finger_trees.php
Below the second picture he mentions the use of finger trees in text editors to implement an extremely cheap "undo" feature, but I'm sure you can see the validity of the tree for your problem as well.
There are no global variables in C#. You should have such an variable as an instance variable in your form (or better yet, in a model for which your form is a view), and that is perfectly fine.
This is a very simple and stupid solution. I would use a MVP design pattern for this but here the fastest and simple solution:
//Declare a flag to block the processing of your event
private bool isEventBlocked = false;
private void OnTextChanged(object sender, EventArgs e)
{
if(!isEventBlocked)
{
//do your stuff
}
}
private void OnNewFile() //OR OnOpenFile()
{
try
{
isEventBlocked = true;
CreateFile();
}
catch
{
//manage exception
}
finally
{
isEventBlocked = false;
}
}