Write text to notepad with C#/Win32

2019-03-25 05:33发布

问题:

I'm messing around with Win32 API and windows messaging trying to figure out how things work and I found this question very helpful.

I'd like to improve upon the solution provided there so that it appends the text instead of just replacing the text in notepad via WM_SETTEXT.

My question is, how would I use WM_GETTEXTLENGHT, followed by WM_GETTEXT, to get the current text in the notepad window so I could then append new text to it before using WM_SETTEXT?

Does using WM_XXXTEXT work on both 32 and 64-bit machines? If there is a lot of text in notepad would the proposed get/set algorithm still work or would it hog a bunch of resources? If so, is there another way to append text to the notepad window without copying everything in it first?

Thanks for you help!!

UPDATE:

Here is the code I came up with based on David Heffernan's help and Google/SO cut n pasting. As I'm new to the Win32API and copied many lines from different sources I'd appreciate any and all feedback.

[DllImport("User32.dll", CharSet = CharSet.Auto)]
        extern static IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, [In] string lpClassName, [In] string lpWindowName);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        extern static int SendMessageGetTextLength(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);

        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, int lParam);

        const int WM_GETTEXTLENGTH = 0x000E;

        const int EM_SETSEL = 0x00B1;

        const int EM_REPLACESEL = 0x00C2;

        public void testAppendText(string text)
        {
            Process[] notepads = Process.GetProcessesByName("notepad");
            if (notepads.Length == 0) return;
            if (notepads[0] != null)
            {
                IntPtr editBox = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);
                int length = SendMessageGetTextLength(editBox, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
                SendMessage(editBox, EM_SETSEL, length, length);
                SendMessage(editBox, EM_REPLACESEL, 1, text);
            }

        } 

回答1:

Send EM_SETSEL to put the caret to the end of the edit window. Then send EM_REPLACESEL to append text.

This is much better than reading the entire contents, appending your addition and then setting the entire contents if the edit control contains a large amount of text.

These methods can cross 32/64 bit process boundaries without difficulty.