This question has just come up on the .NetCF newsgroup. P/Invoke is again to the rescue:
public void SaveTextBox(TextBox textBox, string fileName)
{
StringBuilder buffer = new StringBuilder(" ", 255);
// Get TextBox's native handle
textBox.Capture = true;
IntPtr handle = GetCapture();
textBox.Capture = false;
// The EM_GETLINE requires the length of the buffer in the first byte.
buffer[0] = (char)255;
using(StreamWriter writer = new StreamWriter(fileName))
{
// Get line count
int lineCount = SendMessage(handle, EM_GETLINECOUNT, 0, 0);
for(int i=0;i<lineCount;i++)
{
SendMessage(handle, EM_GETLINE, i, buffer);
writer.WriteLine(buffer.ToString());
}
writer.Flush();
}
}
Required P/Invoke declarations:
const int EM_GETLINECOUNT = 0x00BA;
const int EM_GETLINE = 0x00C4;
[DllImport("coredll.dll")]
static extern IntPtr GetCapture();
[DllImport("coredll.dll")]
static extern int SendMessage(IntPtr hwnd, int msg, int wParam, int lParam);
[DllImport("coredll.dll")]
static extern int SendMessage(IntPtr hwnd, int msg, int wParam, StringBuilder lParam);