How to set Selection start based on Mouse Position WinForms - c#

I need to set Selection start of a text box based on the mouse position, i tried to load the text box on Double Click, once the text box is loaded, i need to set the selection start based on the Mouse position. (i.e) if a text box contains some values like "abcdef", if the mouse cursor is near "c" when textbox is loaded, then the selection start should be after "c".
I have also tried this
textBox.GetCharIndexFromPosition(e.Location);
but i didn't get it right,
Thanks in advance.
Regards,
Venkatesan R

Putting #Reza's code in the correct event will work just fine:
private void textBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
textBox.Text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // load the text data here
// now position the caret onto the mouse position
textBox.SelectionStart = textBox.GetCharIndexFromPosition(e.Location);
// and clear a selection
textBox.SelectionLength = 0;
}
Note that you need to use the MouseDoubleClick, not the simple DoubleClick or else you miss the e.Location param!
This is the simplest and most direct way to get the mouse coordinates relative to the TextBox.
If your loading method is complex you can call it by passing in the MouseEventArgs e but simply calling it instead of the textBox.Text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; is the most natural way.
If you want to you could also use
textBox.SelectionStart = textBoxtextBox1.PointToClient(Control.MousePosition));
This will work in any event or method. PointToClient will calulate the relative position from the screen position Control.MousePosition.

Related

Click interface Clarification (Entry-Level)

I'm trying to create a graph editor using WinForms.
I have a picture box, whenever I click on it the program draws a vertex by creating a label about 15px in size where I store a string, the location, etc.
I can draw the edges by drawing lines from location to location, but I need other boxes to do this, I wonder if there is a way to do this purely by touch (with the mouse cursor).
I need some kind of object that if clicked will start an event that will draw an edge up to the vertex I click next. I considered adding little picture boxes instead of labels, but the labels are convenient for storing the name of the vertexes, also I think adding both a label and an other box in the same position may hide one of the objects.
You can get the x and y coordinate's of the mouse on a user controls click event.
I would store the coordinate's of the last point you clicked on outside of the mouse click event and then draw a line from the last point to the new point.
lastPoint = null;
private void userControl_MouseClick(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left)
{
Point newPoint = e.Location;
if(lastPoint != null)
{
drawLine(lastPoint, newPoint);
}
lastPoint = newPoint;
}
}
Hope this helps.

RichTextBox.GetLineFromCharIndex does not work correctly. How to get the CORRECT line index in which the cursor currently is?

I'm trying to find a way to get the line's index in which the cursor is currently blinking in a RichTextBox control, and display it in a Label.
First I've tried GetLineFromCharIndex(), but when I press an arrow key, it does not updates itself at the first time. I've created this example:
These are my lines:
this
is
my
example
when I wrote these, the line index was shown correctly. Now let's say my cursor is blinking right now in the fourth line (I = the cursor)
this
is
my
eIxample
The index is now correctly displayed as 3. But now if I press an up arrow key, the cursor will blink in the "my" line, but the index will be still 3.
If I write the indexes every time I pressed the up key to the console, the result looks like this:
//Output:
3
3
2
1
I've tried to use Regex and a foreach loop as well, but they gave me the perfectly same result.
Can anyone give me a good advice how to write a code that always updates and shows the correct index of the line in which the cursor currently is?
Thanks
You are probably handling the KeyDown event of RichTextBox, which fires before the SelectionStart property is changed to the cursor position, so that method always gives you the line index for the previous cursor position. Handle the KeyUp event and your problem should be fixed:
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
int selectionStart = richTextBox1.SelectionStart;
int lineIndex = richTextBox1.GetLineFromCharIndex(selectionStart);
label1.Text = lineIndex.ToString();
}

How to get Keyboard cursor position as Point in textbox

I want to get Keyboard cursor position in TextBox or RichTextBox. On WinFrom I did this by using this code
Point p = rtb.GetPositionFromCharIndex(rtb.SelectionStart);
p.Y += (int)rtb.Font.GetHeight()*2;
lstboxIntelli.Location = p;
lstboxbIntelli.Show();
ActiveControl = lstboxIntelli;
But in WPF I cant get GetPositionFromCharIndex property is there any other way to achieved this
I want to position a Listbox right under the keyboard cursor (Like Intellisense)
Any help will be appreciate
In WPF TextBox you can get caret position in multiple ways:
By accessing TextBox.SelectionStart and TextBox.SelectionLength properties.
TextBox.CaretIndex property.
Unfortunately there is no GetPositionFromCharIndex in TextBox so you'll have to do a little trick using GetRectFromCharacterIndex to get starting point for intellisense:
var rect = rtb.GetRectFromCharacterIndex(rtb.CaretIndex);
var point = rect.BottomRight;
Note: We are using BottomRight to make put intellisense in proper place.

progress bar click => change current track play position

i am making a music player in winforms. i have a progress bar and when i click on a position along the progress bar, i want to get the int for that position ( from 1 to 100 , i.e. for when i want to get to a certain point in my song ) . How can i do that ?
Regards,
Alexandru Badescu
Use TrackBar control, and this is may an advance one, I hope it helps you.
Good luck.
Try this:
'Using The Click or MouseDown or any Mouse Event
Dim Value As Integer= Me.PointToClient(MousePosition).X-Progressbar.Bounds.X
Progressbar.value= Value
you can use a control that have to be placed on the progress bar --like a small bullet .
now if you use the code
progressbar1.value=control.location.x/y
place the name of the control at the position of control x/y decides the coordinates.
make a note that you have to move the control on the progress bar for simplifications use a picture box and use the keydown event to move it side by side
This one brings up a value in relation to the position where the click was done on the progressbar. The value range here is calculated from 0 to 100%. Its also in relation to the width of the progressbar so the range will stay fixed to percentage logic.
private void progressBar1_Click(object sender, EventArgs e)
{
// Get mouse position(x) minus the width of the progressbar (so beginning of the progressbar is mousepos = 0 //
float absoluteMouse = (PointToClient(MousePosition).X - progressBar1.Bounds.X);
// Calculate the factor for converting the position (progbarWidth/100) //
float calcFactor = progressBar1.Width / (float)progressBar1.Maximum;
// In the end convert the absolute mouse value to a relative mouse value by dividing the absolute mouse by the calcfactor //
float relativeMouse = absoluteMouse / calcFactor;
// Set the calculated relative value to the progressbar //
progressBar1.Value = Convert.ToInt32(relativeMouse);
}
I know this question was asked a long time ago, but it was out of the right solution. Here it is now.
Well you could use a picturebox to simulate a progress bar ... have a method to partially fill it based on current progress, and wire up the MouseDown event (this will provide you with the mouse position which you can then scale accordingly).

How Do I scroll to a string in a Rich Text Box

I ahve a RTB with sufficent text that scrolling is needed
user enters a string and I highlight all occurrences using a combination of Find and Select which is great but now I want the ability for a user to press Next and the next higlighted instance should be visible say 2at /3rd of the bounding rectangle ( I would even settle for at the top of the bound.
How do I scroll to an index basically ( I am caching the indices as I find and markup )
oh also this is C# Winforms .NET 2.0
Set the selection start to the next location, and then use ScrollToCaret to scroll to that location in the rich text box.
rText1.SelectionStart = i
rText1.ScrollToCaret()
private void myrichTextBox_TextChanged(object sender, EventArgs e)
{
myrichTextBox.SelectionStart = myrichTextBox.Text.Length; //Set the current caret position at the end
myrichTextBox.ScrollToCaret(); //Now scroll it automatically
}

Categories

Resources