Reputation: 2438
I want to write text to the currently selected application but its writing junk and causing weird things to happen.
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Runtime.InteropServices;
namespace i_allbwn
{
class Program
{
static void Main(string[] args)
{
Thread.Sleep(500);
ActionWithChance.brif_allbwn();
Console.ReadKey();
}
}
class ActionWithChance
{
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public const int KEYEVENTF_EXTENDEDKEY = 0x0001; //Key down flag
public const int KEYEVENTF_KEYUP = 0x0002; //Key up flag
public static void brif_allbwn()
{
argraffu(new String[] {
"line1",
"line2",
"line3",
}
);
}
public static void allbwn(Byte[] Name)
{
for (int i = 0; i < Name.Length; i++)
{
Console.WriteLine("Writing " + (Char)Name[i]);
keybd_event((Byte)Name[i], 0, KEYEVENTF_EXTENDEDKEY, 0);
Thread.Sleep(10);
keybd_event((Byte)Name[i], 0, KEYEVENTF_KEYUP, 0);
}
}
public static void argraffu(String[] text)
{
foreach (String s in text)
{
allbwn(ToByteArray(s));
keybd_event((Byte)'\r', 0, KEYEVENTF_EXTENDEDKEY, 0);
Thread.Sleep(10);
keybd_event((Byte)'\r', 0, KEYEVENTF_KEYUP, 0);
}
}
public static Byte[] ToByteArray(String StringToConvert)
{
Char[] CharArray = StringToConvert.ToCharArray();
Byte[] ByteArray = new Byte[CharArray.Length];
for (int i = 0; i < CharArray.Length; i++)
{
ByteArray[i] = Convert.ToByte(CharArray[i]);
}
return ByteArray;
}
}
}
Upvotes: 1
Views: 1687
Reputation: 7397
The Autoit library makes it really easy to interact with external windows.
Install the nuget package called AutoItX.Dotnet
Then it's just a matter of:
using AutoIt;
class Program
{
static void Main(string[] args)
{
AutoItX.Run("notepad.exe", null);
AutoItX.WinWait("Untitled - Notepad");
AutoItX.ControlSend("Untitled - Notepad", "", "[CLASSNN:Edit1]", "testing");
//ControlSend is the ideal way to send text, but you can also pretend text was typed into the keyboard:
AutoItX.Send("howdy pilgrim");
}
}
Upvotes: 1
Reputation: 939
My functions for doing it are like this:
public const Int32 WM_CHAR = 0x0102;
public void SendKeys(string message)
{
foreach (char c in message)
{
int charValue = c;
IntPtr val = new IntPtr((Int32)c);
SendMessage(WindowHandle, WM_CHAR, val, new IntPtr(0));
}
}
Basically what I'm doing is getting the handle of the application, e.g:
Process proc = Process.GetProcessesByName("Notepad")[0];
Then getting the handle with proc.MainModule.Handle()
Upvotes: 1