web-dev-qa-db-fra.com

Comment envoyer du texte au Bloc-notes en C # / Win32?

J'essaie d'utiliser SendMessage vers le Bloc-notes, afin de pouvoir insérer du texte écrit sans faire du Bloc-notes la fenêtre active.

J'ai fait quelque chose comme ça dans le passé en utilisant SendText, mais cela nécessitait de donner le focus au Bloc-notes.

Maintenant, je récupère d'abord le handle de Windows:

Process[] processes = Process.GetProcessesByName("notepad");
Console.WriteLine(processes[0].MainWindowHandle.ToString());

J'ai confirmé qu'il s'agit de la bonne poignée pour le Bloc-notes, la même que celle indiquée dans Windows Task Manager.

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

À partir de là, je n'ai pas réussi à faire fonctionner SendMessage dans toutes mes expérimentations. Suis-je dans la mauvaise direction?

31
lolcat
    [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 button1_Click(object sender, EventArgs e)
    {
        Process [] notepads=Process.GetProcessesByName("notepad");
        if(notepads.Length==0)return;            
        if (notepads[0] != null)
        {
            IntPtr child= FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);
            SendMessage(child, 0x000C, 0, textBox1.Text);
        }
    }

WM_SETTEXT = 0x000c

45
ebattulga

Vous devez d'abord trouver la fenêtre enfant où le texte est entré. Pour ce faire, recherchez la fenêtre enfant avec la classe de fenêtre "Modifier". Une fois que vous avez cette poignée de fenêtre, utilisez WM_GETTEXT pour obtenir le texte qui est déjà entré, puis modifiez ce texte (par exemple, ajoutez le vôtre), puis utilisez WM_SETTEXT pour renvoyer le texte modifié.

6
Stefan
using System.Diagnostics;
using System.Runtime.InteropServices;

static class Notepad
{
    #region Imports
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

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

    //this is a constant indicating the window that we want to send a text message
    const int WM_SETTEXT = 0X000C;
    #endregion


    public static void SendText(string text)
    {
        Process notepad = Process.Start(@"notepad.exe");
        System.Threading.Thread.Sleep(50);
        IntPtr notepadTextbox = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero, "Edit", null);
        SendMessage(notepadTextbox, WM_SETTEXT, 0, text);
    }
}
3
Brian