2013-02-15 84 views
0

我想將文本寫入當前選定的應用程序,但其寫入垃圾並導致奇怪的事情發生。將文本寫入另一個窗口

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; 

     } 

    } 
} 
+0

什麼是其他應用程序控制臺應用程序?你如何將鍵盤焦點設置到其他應用程序?最後,爲什麼開始睡覺? – 2013-02-15 22:41:46

+0

另一個應用程序不適用,因爲它可能是任何接受文本輸入的東西。通過點擊應用程序睡眠僅用於測試目的,以便它不會立即鍵入測試文本並完成之前我點擊其他應用程序 – 2013-02-16 01:37:09

+0

使用SendKeys,http://msdn.microsoft.com/en-us/library/ system.windows.forms.sendkeys.aspx – 2013-02-16 10:28:17

回答

0

我這樣做它的功能是這樣的:

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()

相關問題