How do I copy text from a c# Application to Notepad.exe under Windows 11?

212 Views Asked by At

I am using the following code to copy text from a c# application to Notepad.exe:

    [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
    [DllImport("User32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);

    private void btnShowLog_Click(object sender, EventArgs e)
    {
        int count = 0;
        var notepad = Process.Start("notepad.exe");
        notepad.WaitForInputIdle();

        while (notepad == null && count < 20)
        {
            Thread.Sleep(500);
            count++;
        }

        Clipboard.SetText(txbLog.Text);
        SendMessage(FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), "Edit", null), 0x000C, 0, txbLog.Text);
    }

For Windows 10 this works fine.

For Windows 11 it does not. Notepad is opened, but no text is paste.

I think, this is because in Windows 11 Tabs were added to Notepad so that the internal structure of the program was changed.

Does anybody know how I have to change my code so that it works for Windows 11?

Edit: The code in the answers of the linked questions does not work either. I'm getting the desired result for Windows 10, but not for Windows 11.

0

There are 0 best solutions below