Or maybe at least get the data of notepad
As the others have said, it's not the best approach by far...
...but sure, you can actually do that.
Here's an example that retrieves the contents of all open Notepad instances and spits them out in the Console:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private const int WM_GETTEXT = 0xd;
private const int WM_GETTEXTLENGTH = 0xe;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, StringBuilder lParam);
private void button1_Click(System.Object sender, System.EventArgs e)
{
System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName("notepad");
foreach(System.Diagnostics.Process p in ps)
{
IntPtr editWnd = FindWindowEx(p.MainWindowHandle, IntPtr.Zero, "Edit", "");
string sTemp = GetText(editWnd);
Console.WriteLine(p.MainWindowTitle);
Console.WriteLine("------------------------------");
Console.WriteLine(sTemp);
Console.WriteLine("------------------------------");
Console.WriteLine("");
}
}
private string GetText(IntPtr hWnd)
{
int textLength = SendMessage(hWnd, WM_GETTEXTLENGTH, 0, 0) + 1;
System.Text.StringBuilder sb = new System.Text.StringBuilder(textLength);
if (textLength > 0)
{
SendMessage(hWnd, WM_GETTEXT, textLength, sb);
}
return sb.ToString();
}
}
This approach is specific to Notepad (it's not a generic approach to any application). We're using FindWindowEx() to find a child window called "Edit", that is a direct child of the main application window. You can use tools like Spy++ to figure out the window hierarchy of an application to help solve problems like these. In situations where the target window is buried more deeply, or may be one of many windows of the same type at a particular level, you may need to use several other APIs to get a handle to the correct window. This is a complex topic and there are several other low level API approaches that can be used.