TextBox with vertical scrollbar on the left side - c#

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

Related

How to Disable Flashing Text Line?

I have a textbox control and I've simulated it to be like a label by turning the readonly and border property to true and none respectively so it can highlighted. Everything works fine but when I click on the textbox, it shows the flashing text symbol (it's a flashing l that indicating that you can type here, don't know what's it called).
If I turn enabled property to false, it disappears but it can't be highlighted and the text is grayed out.
Is there a way to fix this? Like another type of control?
The little "flashing text line" is called a caret. It is like a cursor (which is the thing you move with the mouse), except that it appears in text.
And what you describe in the question is normal behavior. You see the exact same thing in the Windows shell. Right-click on any icon in any location (e.g., the desktop), and open its "Properties" window. Then click on any one of the property labels (e.g., the path under "Location"). You'll see the same thing.
There's a caret there, flashing just beyond the letter "i", and you can see even see that the selection is highlighted. This is by design, and the selection highlighting is an important clue.
The reason why you would use a read-only textbox instead of a label is to allow the user to select text out of the control. If you don't want to allow this, then just use a label.
If you absolutely must use a read-only textbox and still want to hide the caret, then you can p/invoke the HideCaret function. By calling this function as soon as your textbox control gets the focus, it won't ever show the caret. However, every call to HideCaret must be paired with a call to ShowCaret, so you'll need to call ShowCaret when your textbox control loses the focus.
You could wire up handlers to the GotFocus and LostFocus events for your particular textbox control and place the code in there. But it is cleaner to do this in a derived control class, especially if you want to have multiple textboxes that behave the same way. Something like this (code untested):
internal class NativeMethods
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowCaret(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool HideCaret(IntPtr hwnd);
}
public class ReadOnlyTextBox : System.Windows.Forms.TextBox
{
public ReadOnlyTextBox()
{
this.ReadOnly = true;
}
protected override void OnGotFocus(EventArgs e)
{
NativeMethods.HideCaret(this.Handle);
}
protected override void OnLostFocus(EventArgs e)
{
NativeMethods.ShowCaret(this.Handle);
}
}
Text symbol will flash i don't know weather you can disable flashing better you can use label i think that is good check the visibility property of text box may be it will be false that's why you cant able to see.
through code also you can enable visibility
textboxname.visible= true;
tweak this css properity for your project.
input[disabled] {
background-color: #b5f0fa;
border: 1px solid;
color: Black;
font-weight: bold;
}

C# program to paste text from clipbord to any point where mouse clicks

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 Winforms RichTextBox control, how can I make the space BELOW a last-line link NOT clickable?

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.

How to automatically show beginning of text in TextBox

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);

Databound controls "flashing" as they are refreshed

It's a small thing but I was just wondering...
Visual Studio 2008, C#.
I have a master-detail form with databound controls. When user selects the record in a listbox, all the details are updated in multiple databound controls on the form.
As it happens, they kind of 'flash', or blink, when repopulated with new data and it's sort of like an electrical wave going across the form in a fraction of second :) don't know how to explain it better
Not a big deal, but still, it looks "shaky" and ugly, so, for the sake of ellegance, I was just wondering whether there is some easy way to prevent it?
I thought about calling SuspendLayout and ResumeLayout (on the container control), but what events should I handle? listBox_SelectedValueChanged for suspending it, I guess ... but for resuming?
You could prevent the flicker by suspending painting when the control's data is refreshed.
From this stackoverflow question:
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
parent.Refresh();
}
As far as which events to handle, I'm not sure.
I didn't notice that "SuspendLayout" did anything for me, but worth giving it a shot. I think you would want to latch onto the "CurrentChanged" event for when the selected item is changed wholesale.
Have you set the DoubleBuffered (under "behavior" in the props window) to true?
control.DoubleBuffered = true;
A bit 'o history: http://www.codeproject.com/KB/graphics/DoubleBuffering.aspx

Categories

Resources