2012-09-19 54 views
2

我有下面的代碼,允許用戶在可執行文件(即notepad.exe)中寫入,然後單擊開始按鈕它將啓動該過程。接受文本框輸入/返回

但是,如何使文本框接受輸入/返回鍵?我把AcceptsReturn=true,但它沒有做任何事情。我也在Visual Studio中設置了屬性Accept Return = True - 仍然沒有。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Diagnostics; 

namespace process_list 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 

      string text = textBox1.Text; 
      Process process = new Process(); 
      process.StartInfo.FileName = text; 
      process.Start(); 

     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
      textBox1.AcceptsReturn = true; 
     } 
    } 
} 

回答

8

將表格的AcceptButton設置爲您的按鈕。那麼你不需要AcceptsReturn,因爲輸入自動觸發按鈕。

public Form1() 
{ 
    InitializeComponent(); 
    this.AcceptButton = button1; 
} 
+0

輝煌 - 非常感謝! – lara400

5

添加keydown事件的方法來textBox1的和方法內做到這一點

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.Enter) 
      button1_Click(sender, e); 
    } 
+1

+1如果您在表單中有多個文本框並且每個文本框都對應一個默認按鈕,那麼這非常有幫助。對於例如一個搜索框和一個按鈕。 –