title: Write text to notepad with C#/Win32
body: <p>I'm messing around with Win32 API and windows messaging trying to figure out how things work and I found this <a href="https://stackoverflow.com/questions/523405/how-to-send-text-to-notepad-in-c-win32">question very helpful</a>.</p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>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?</p>
  
  <p>Thanks for you help!!</p>
  
  <p>UPDATE:</p>
  
  <p>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.</p>
  
  <pre><code>[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);
              }
  
          } 
  </code></pre>