2013-08-07 53 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"); 
    } 
    } 
} 
相关问题