2013-08-07 50 views
1

我有一個程序使用KeyPress事件來添加一個新的角色到一個新的Label,有點像控制檯應用程序。 我需要將Input方法添加到我的程序中,所以當我按Enter鍵而不是執行函數時,它會返回一個字符串。我曾嘗試使KeyPress事件返回一個字符串,但由於顯而易見的原因它不起作用,我該如何完成這項工作?我如何等待一個字符串返回一個值?

注意:通過「返回字符串」我的意思是;

如果我在哪裏要求Console等待輸入,我仍然會使用KeyPress事件,但它會返回用戶的字符串/輸入。

我希望你明白我已經寫的代碼,請注意,它延伸到其他

我的按鍵事件處理函數:

private void Form1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (e.KeyChar == '\b') // Backspace 
     { 
      if (ll.Text != "_" && ActualText != "") // Are there any characters to remove? 
      { 
       ActualText = ll.Text.Substring(0, ActualText.Length - 1); 
       ll.Text = ActualText + "_"; 
      } 

     } 
     else 
      if (e.KeyChar == (char)13) 
      { 
       if (!inputmode) 
       { 
        foreach (KeyValuePair<string, Action> cm in Base.Command()) 
        { 

         if (ActualText == cm.Key) 
         { 
          print(ActualText); 
          cm.Value(); 

         } 
        } 
       } 
       else 
       { 
        inputmode = false; 
        lastInput = ActualText; 
        print("Input >> "+lastInput); 
       } 
       ActualText = ""; 
       ll.Text = ActualText + "_"; 
      } 
      else 
      if (!Char.IsControl(e.KeyChar)) // Ignore control chars such as Enter. 
      { 
       ActualText = ActualText + e.KeyChar.ToString(); 
       ll.Text = ActualText + "_"; 
      } 
    } 
+18

你怎麼樣發佈您的代碼? –

+0

什麼樣的程序,它是一個控制檯應用程序/ WPF/Winforms的? – ywm

+0

它是一個Windows窗體應用程序。 –

回答

2

你的問題是有點不清楚,但如果我這樣做是正確,則該解決方案,而不是返回一個字符串,你顯然不能在KeyPress活動,提高自己的事件,像這樣

public delegate void EnterPressedHndlr(string myString); 

public partial class Form1 : Form 
{ 
    public event EnterPressedHndlr EnterPressed; 

    void Form1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
    //your calculation 
    if (EnterPressed != null) 
    { 
     EnterPressed("your data"); 
    } 
    } 
} 
相關問題