I have very long text and put it into TextBox. I want to display automatically the beginning of the text not the end. But TextBox automatically show the end of my text.
What can I do to achieve it.
I use SelectionStart method to put cursor at the beginning of text in TextBox in order to implement some simple IntelliSense so preferred solution would not use methods that move cursor.
You could always initially put a smaller value in the textbox then upon your criteria for displaying the full text append the remaining portion of the full text.
Example:
textBox.text = someString.Substring(0, x);
then when needed do
textBox.AppendText(someString.Substring(x+1));
I assume you are using WinForms.
Update: Strange. The struck-out code below workes as described if executed in the form constructor, but not later in the form lifecycle (e.g. a button click handler).
Note that if you have already used SelectionStart to put the cursor at the beginning of the text (e.g., via textBox.SelectionStart = 0;), then all that needs follow is textBox.ScrollToCaret();.
Consider using the textBox.AppendText(someLongString) method when adding text to your text box instead of textBox.Text = someLongString.
If you must wipe out the current text before assigning the new text, use textBox.Text = string.Empty; followed by a call to textBox.AppendText();
You could use owner-draw to override the rendering of the textbox when it doesn't have the input focus. That would trivially give you complete control of what it shows when, without breaking any of the actual editing functionality of the textbox by trying to hack it.
You can send a Win32 scroll message to the underlying textbox handle via P/Invoke:
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
// From User32.dll
private const int WM_VSCROLL = 277;
private const int SB_TOP = 6;
SendMessage(yourTextBox.Handle, WM_VSCROLL, (IntPtr)SB_TOP, IntPtr.Zero);
Related
I want to paste text from my text box or rich text box in C# windows form application to out side of the form for example:
//on a button click event
textbox1.text=Clipboard.SetText(); // this will set text to clipboard
now I want when I click in address bar of Firefox or Google chrome to get the same text as I typed in my windows form application, as I can do it by CTRL+V but I want a C# program to do so for me and get text from clipboard when ever I click in address bar or rename a folder.
You could just turn on some windows disability settings, If dragging or pasting is too awkward.
If you really want to implement this, you need a global hook on the mouse so you can recieve mouse events from outside your application. See here or perhaps here.
Then you have a problem, do you want to paste anywhere or just in address bars. First you'll have to define what an address bar window is and work out if that is what has the focus.
Its a lot of effort and the behaviour is not especially desirable. If you really want this, please expand your question and improve its readability so that this post will be useful to future visitors.
This is completely untested, and I've never used these DLL calls in C#, but hopefully it will do the trick or at least come close...
public class Win32
{
public const uint WM_SETTEXT = 0x000c;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, string lParam);
[DllImport("user32.dll")]
static extern IntPtr WindowFromPoint(int xPoint, int yPoint);
}
Elsewhere in the code...
IntPtr theHandle = WindowFromPoint(Cursor.Position.X, Cursor.Position.Y);
if (theHandle != null)
{
long res = Win32.SendMessage(theHandle, WM_SETTEXT, IntPtr.Zero, Clipboard.GetText());
}
Note: I'm not entirely sure that WindowFromPiont will get the handle of the child control (i.e. the actual textbox) of another window, rather than the handle of the window itself. You might have to find the child by the cursor position. Been a long time since I've done something like this, unfortunately.
Also, if you want to get a fancier with the acquisition of the window handle, see this question: getting active window name based on mouse clicks in c#
In a Windows forms C# application, I have a number of RichTextBox controls that display a link as the last line of the text box, with no line break after.
The issue is that ALL of the white space that is physically below the link will be a clickable link. I understand that empty white space below text generally serves as "part" of that line in windows--for example, put your cursor just below this post, and click and drag--you will select the last line. But generally this does not include clickable links. Try it with the title of this post--you can select the title, but your cursor is not the clickable "hand" until you are actually directly over the title.
I could get around this by changing my data to always include a trailing line break, or modify the point where I'm setting the text of the box to always add one. But both of those seem messy. Is there no way to make a RichTextBox's links act more like links in a web browser?
I can reproduce this behavior by creating a sample WinForms application, dropping in a RichTextBox, and using the designer to set the text to "http://www.google.com" Anywhere BELOW the link will show the hand cursor.
I'm using Windows 7 / VS2010 / C# / .net Framework 4.0
Thanks for the advice.
Anywhere BELOW the link will show the hand cursor.
You need to put a line break to see the text cursor below the link not the hand cursor. Its by design.
I could get around this by changing my data to always include a
trailing line break, or modify the point where I'm setting the text of
the box to always add one. But both of those seem messy. Is there no
way to make a RichTextBox's links act more like links in a web
browser?
No. Put a line break after. Or set the RichTexbox DetectUrls property to false. Or as Hans mentioned use a Web Browser. Or use a 3rd party or open source RichTextBox control.
It would be good if the Cursor change event fired when hovering over a hyperlink but it doesn't :(
It would be good if the Cursor change event fired when hovering over a hyperlink but it doesn't :(
Jeremy's comment gave me an idea: surely the native RichTextBox control does receive some type of notification when the user hovers over a hyperlink, it apparently just is not exposed by the WinForms wrapper class.
A bit of research confirms my supposition. A RichTextBox control that is set to detect hyperlinks sends a EN_LINK notification to its parent through the WM_NOTIFY message. By processing these EN_LINK notifications, then, you can override its behavior when a hyperlink is hovered.
The WinForms wrapper handles all of this in private code and does not allow the client to have any direct control over this behavior. But by overriding the parent window's (i.e., your form) window procedure (WndProc), you can intercept WM_NOTIFY messages manually and watch for EN_LINK notifications.
It takes a bit of code, but it works. For example, if you suppress the WM_SETCURSOR message for all EN_LINK notifications, you won't see the hand cursor at all.
[StructLayout(LayoutKind.Sequential)]
struct CHARRANGE
{
public int cpMin;
public int cpMax;
};
[StructLayout(LayoutKind.Sequential)]
struct NMHDR
{
public IntPtr hwndFrom;
public IntPtr idFrom;
public int code;
};
[StructLayout(LayoutKind.Sequential)]
struct ENLINK
{
public NMHDR nmhdr;
public int msg;
public IntPtr wParam;
public IntPtr lParam;
public CHARRANGE chrg;
};
public class MyForm : Form
{
// ... other code ...
protected override void WndProc(ref Message m)
{
const int WM_NOTIFY = 0x004E;
const int EN_LINK = 0x070B;
const int WM_SETCURSOR = 0x0020;
if (m.Msg == WM_NOTIFY)
{
NMHDR nmhdr = (NMHDR)m.GetLParam(typeof(NMHDR));
if (nmhdr.code == EN_LINK)
{
ENLINK enlink = (ENLINK)m.GetLParam(typeof(ENLINK));
if (enlink.msg == WM_SETCURSOR)
{
// Set the result to indicate this message has been handled,
// and return without calling the default window procedure.
m.Result = (IntPtr)1;
return;
}
}
}
base.WndProc(ref m);
}
}
Unfortunately, that's the easy part. Now comes the ugly hack where we work around the default behavior of the control that you describe, where it treats the remainder of the control's height as part of the last line if the last line is a hyperlink.
To do this, we need to get the current position of the mouse pointer and compare it against the position of the hyperlink text that the control has detected. If the mouse pointer is within the hyperlinked line, we allow the default behavior and show the hand cursor. Otherwise, we suppress the hand cursor. See the commented code below for a potentially better explanation of the process (obviously, rtb is your RichTextBox control):
protected override void WndProc(ref Message m)
{
const int WM_NOTIFY = 0x004E;
const int EN_LINK = 0x070B;
const int WM_SETCURSOR = 0x0020;
if (m.Msg == WM_NOTIFY)
{
NMHDR nmhdr = (NMHDR)m.GetLParam(typeof(NMHDR));
if (nmhdr.code == EN_LINK)
{
ENLINK enlink = (ENLINK)m.GetLParam(typeof(ENLINK));
if (enlink.msg == WM_SETCURSOR)
{
// Get the position of the last line of text in the RichTextBox.
Point ptLastLine = rtb.GetPositionFromCharIndex(rtb.TextLength);
// That point was in client coordinates, so convert it to
// screen coordinates so that we can match it against the
// position of the mouse pointer.
ptLastLine = rtb.PointToScreen(ptLastLine);
// Determine the height of a line of text in the RichTextBox.
//
// For this simple demo, it doesn't matter which line we use for
// this since they all use the same size and style. However, you
// cannot generally rely on this being the case.
Size szTextLine = TextRenderer.MeasureText(rtb.Lines[0], rtb.Font);
// Then add that text height to the vertical position of the
// last line of text in the RichTextBox.
ptLastLine.Y += szTextLine.Height;
// Now that we know the maximum height of all lines of text in the
// RichTextBox, we can compare that to the pointer position.
if (Cursor.Position.Y > ptLastLine.Y)
{
// If the mouse pointer is beyond the last line of text,
// do not treat it as a hyperlink.
m.Result = (IntPtr)1;
return;
}
}
}
}
base.WndProc(ref m);
}
Tested and working… But did I mention that this is an ugly hack? Treat it more like a proof of concept. I certainly don't recommend using it in production code. I'm in fairly strong agreement with Hans and Jeremy that you should either take the simpler approach of adding a line break, or use a more appropriate control designed to display hyperlinks.
I'm developing a Windows Forms application in C#, which has a multiline TextBox control on a form.
Due to specific (irrelevant) reasons, this TextBox needs a vertical scrollbar on the left side of the TextBox control. I've off course searched for a solution, but I couldn't find any... so my questions are:
1) Is there a way to make the automatic vertical scrollbar of a TextBox control (or a usercontrol derived from TextBox or TextBoxBase) appear on the left instead of the right? This is the preferred method, since all scolling is then still handled by the control. Since chancing the RightToLeft property for such a TextBox actually moves the scrollbar to the left, I feel there must be a hack to be exploited here.
or
2) Is there a message that I can intercept with my IMessageFilter implementation when the TextBox is scrolled, even though it doesn't have scrollbars? I.e. a user can scroll using the arrow keys and the textbox will move lines up and down, but I can't find any messages fired when that occurs.
Maybe another idea of how to accomplish this?
Edit to add: The text needs to be aligned to the right horizontally! Otherwise I would have solved it already.
New edit as of 11/03/2014: Okay, after BenVlodgi's comment I started having doubts about my own sanity. So I created a test project and now I remember why setting RightToLeft to Yes was not working.
The image below shows a regular TextBox on the left with that setting. The scrollbar is on the left and the text on the right, but the text is not shown properly. The period at the end of the sentence is moved in front of the sentence.
The second TextBox control is the one suggested in LarsTech's answer, which functions correctly and does not move any punctuation.
Therefore, I accept and reward the bounty to LarsTech's answer.
I took some of the example code from Rachel Gallen's link and made this version of the TextBox:
public class TextBoxWithScrollLeft : TextBox {
private const int GWL_EXSTYLE = -20;
private const int WS_EX_LEFTSCROLLBAR = 16384;
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
int style = GetWindowLong(Handle, GWL_EXSTYLE);
style = style | WS_EX_LEFTSCROLLBAR;
SetWindowLong(Handle, GWL_EXSTYLE, style);
}
}
I've never done it before, but the results seem to have worked:
By setting the RightToLeft property true. But it said the content would also be from right to left, so I don't know if that would solve your problem...But that's a way to set the scrollbar on the left hand side.
http://bytes.com/topic/c-sharp/answers/255138-scrollbar-position
I have a DateTimePicker cell in my DataGridView. I'd like to be able to enter edit mode and drop the calendar when a button is clicked. I'm able to do the first part without difficulty but the second isn't working. If I have a standalone DateTimePicker the SendKeys call does work as expected.
//Select the cell and enter edit mode - works
myDGV.CurrentCell = myDGV[calColumn.Index, e.RowIndex];
myDGV.BeginEdit(true);
//Send an ALt-Down keystroke to drop the calendar - doesn't work
SendKeys.SendWait("%{DOWN}");
From debugging I believe that the problem is that the keystroke is being sent to the DGV and not the specific cell that I'm trying to edit. The reason I think is is that I've put code to log keys received by the grids KeyPress and KeyDown events. They log my arrowing around the grid and the keys sent by SendKeys, but not those from when I'm editing a cell by typing in it.
Please see my answer on C# Winforms DataGridView Time Column. I believe it will fit your needs perfectly. You can also use it for a column that has a ComboBox.
I recently revisited this issue because the implementation provided by 0A0D didn't always play nicely with keyboard navigation of the grid (arrows/tab). At times it was possible to bypass the DateTimePicker and enter text into the DataGridViewTextBoxCell. This caused my validation logic to freak out; and after failing to find a way to prevent the slip around from happening I decided to try and get the custom column working again.
The fix turned out to be very simple. I created an extended DateTimePicker with a method to send the keystroke needed to display the calendar.
/// <summary>
/// Extended DateTimePicker with a method to programmatically display the calendar.
/// </summary>
class DateTimePickerEx : DateTimePicker
{
[DllImport("user32.dll")]
private static extern bool PostMessage(
IntPtr hWnd, // handle to destination window
Int32 msg, // message
Int32 wParam, // first message parameter
Int32 lParam // second message parameter
);
const Int32 WM_LBUTTONDOWN = 0x0201;
/// <summary>
/// Displays the calendar input control.
/// </summary>
public void ShowCalendar()
{
Int32 x = Width - 10;
Int32 y = Height / 2;
Int32 lParam = x + y * 0x00010000;
PostMessage(Handle, WM_LBUTTONDOWN, 1, lParam);
}
}
I then modified the MSDN DateTime column example to have CalendarEditingControl inherit from DateTimePickerEx.
Then in the form hosting the DataGridView I used the EditingControl property to call the ShowCalendar() method.
DateTimePickerEx dtp = myDataGridView.EditingControl as DateTimePickerEx;
if (dtp != null)
dtp.ShowCalendar();
I'm creating a function that takes a RichTextBox and has access to a list of keywords & 'badwords'. I need to highlight any keywords & badwords I find in the RichTextBox while the user is typing, which means the function is called every time an editing key is released.
I've written this function, but the words and cursor in the box flicker too much for comfort.
I've discovered a solution--to disable the RichTextBox's ability to repaint itself while I'm editing and formatting its text. However, the only way I know to do this is to override the "WndProc" function and intercept (what I've been about to gather is) the repaint message as follows:
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == 0x00f) {
if (paint)
base.WndProc(ref m);
else
m.Result = IntPtr.Zero;
}
else
base.WndProc(ref m);
}
Where the boolean 'paint' is set to false just before I start highlighting and to true when I finish. But as I said, the function I make must take in a RichTextBox; I cannot use a subclass.
So, is there a way to disable the automatic repainting of a RichTextBox 'from the outside?'
It is an oversight in the RichTextBox class. Other controls, like ListBox, support the BeginUpdate and EndUpdate methods to suppress painting. Those methods generate the WM_SETREDRAW message. RTB in fact supports this message, but they forgot to add the methods.
Just add them yourself. Project + Add Class, paste the code shown below. Compile and drop the control from the top of the toolbox onto your form.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class MyRichTextBox : RichTextBox {
public void BeginUpdate() {
SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)0, IntPtr.Zero);
}
public void EndUpdate() {
SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);
this.Invalidate();
}
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
private const int WM_SETREDRAW = 0x0b;
}
Or P/Invoke SendMessage directly before/after you update the text.
I haven't accumulated enough points to amend Hans' recommendation. So I added this Answer to mention that it may be necessary to request a repaint by calling InvalidateRect. Some Begin/End Update implementations do this automatically upon the final release of the update lock. Similarly in .Net, Control.Invalidate() can be called which invokes the native InvalidateRect function.
MSDN: Finally, the application can call the InvalidateRect function to cause the list box to be repainted.
See WM_SETREDRAW
Your best bet to accomplish what you are trying to do is to create a multithreaded application. You'll want to create one thread that checks the text against your list. This thread will put any instances it finds into a queue. You'll also want to create another thread that does the actual highlighting of the words. Because you'll need to use BeginInvoke() and Invoke() to update the UI, you'll want to make sure you throttle the rate at which this gets called. I'd so no more then 20 times per second. To do this, you'd use code like this:
DateTime lastInvoke=DateTime.Now;
if ((DateTime.Now - lastInvoke).TotalMilliseconds >=42)
{
lastInvoke=DateTime.Now;
...Do your highlighting here...
}
This thread will check your queue for words that need to be highlighted or re-highlighted and will constantly check the queue for any new updates. Hope this makes sense!