Allowing Paste Linux Files Into a TextBox

If you are playing a lot with Linux, sooner or later you will see that pasting files produced by it will usually yield weird results on Windows as far as line ending goes.

You see, Linux uses Line Feed character (LF, ASCII 10) to signal the end of line. Windows uses a combination of Carriage Return and Line Feed (CRLF, ASCII 13+10). When Windows sees CRLF it will go to the next row. If it sees just LF, it will ignore it and you will see all in the same line unless application is a bit smarter. Unfortunately many are not.

Well, not much you can do about other people applications. However, you can ensure your application supports both CRLF and LF as a line ending. The only trick is to split text being pasted by CRLF, LF, and CR and to recombine it using CRLF (on Windows).

To catch paste, we can simply inherit existing TextBox control and override handling of WM_PASTE message:

internal class TextBoxEx : TextBox {
protected override void WndProc(ref Message m) {
if (m.Msg == NativeMethods.WM_PASTE) {
if (Clipboard.ContainsText()) {
var lines = Clipboard.GetText().Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
this.SelectedText = string.Join(Environment.NewLine, lines);
} else {
base.WndProc(ref m);

private static class NativeMethods {
internal const Int32 WM_PASTE = 0x0302;

Whenever you use TextBoxEx instead of TextBox, you will have your multiline paste working whether line ends in CRLF, LF, or even long-forgotten CR.

Leave a Reply

Your email address will not be published. Required fields are marked *