将文本写入另一个窗口
问题描述:
我想将文本写入当前选定的应用程序,但其写入垃圾并导致奇怪的事情发生。将文本写入另一个窗口
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;
}
}
}
答
我这样做它的功能是这样的:
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));
}
}
基本上我做的是让应用程序的处理,如:
Process proc = Process.GetProcessesByName("Notepad")[0];
然后让手柄与proc.MainModule.Handle()
什么是其他应用程序控制台应用程序?你如何将键盘焦点设置到其他应用程序?最后,为什么开始睡觉? – 2013-02-15 22:41:46
另一个应用程序不适用,因为它可能是任何接受文本输入的东西。通过点击应用程序睡眠仅用于测试目的,以便它不会立即键入测试文本并完成之前我点击其他应用程序 – 2013-02-16 01:37:09
使用SendKeys,http://msdn.microsoft.com/en-us/library/ system.windows.forms.sendkeys.aspx – 2013-02-16 10:28:17