2012-07-03 56 views
0

我剛剛從互聯網上看到了這個片段,但它不適用於我。 假設打開一個新的記事本應用程序並添加「asdf」。打開記事本並添加文本不起作用

代碼有問題嗎?

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

void Test() 
{ 
     const int WM_SETTEXT = 0x000C; 

    ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe"); 
    startInfo.UseShellExecute = false; 
    Process notepad = System.Diagnostics.Process.Start(startInfo); 
    SendMessage(notepad.MainWindowHandle, WM_SETTEXT, 0, "asdf"); 
} 
+2

「它不適合我」 - 嗯,它是做什麼的? 'notepad.exe'進程是否啓動?記事本應用程序是否顯示?這些代碼中是否有任何錯誤?你說你「從互聯網上看到這個片段」,但你明白它在做什麼?例如,那個'const'的目的是什麼? – David

+0

哪部分不起作用?記事本是否打開? – Blorgbeard

+0

我試圖打開一個新的記事本然後添加一些文本。從上面的代碼是「asdf」 – yonan2236

回答

0

下面的代碼就可以了你,

[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); 
     } 
    } 
0

試試這個:

[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); 
     void Test() 
     { 
      ProcessStartInfo startInfo = new ProcessStartInfo("notepad.exe"); 
      startInfo.UseShellExecute = false; 
      Process notepad = System.Diagnostics.Process.Start(startInfo); 
      //Wait Until Notpad Opened 
      Thread.Sleep(100); 
      Process[] notepads = Process.GetProcessesByName("notepad"); 
      IntPtr child = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null); 
      SendMessage(child, 0x000c, 0, "test"); 
     } 
2

要確保過程已準備好接受輸入,撥打notepad.WaitForInputIdle()。重要的是使用剛剛創建的進程的MainWindowHandle,而不是任何記事本進程。

[DllImport("user32.dll")] 
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); 

static void ExportToNotepad(string text) 
{ 
    ProcessStartInfo startInfo = new ProcessStartInfo("notepad"); 
    startInfo.UseShellExecute = false; 

    Process notepad = Process.Start(startInfo); 
    notepad.WaitForInputIdle(); 

    IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), null, null); 
    SendMessage(child, 0x000c, 0, text); 
} 
相關問題