2014-06-18 3 views
2

간단한 텍스트 편집기를 개발 중이며 일부 문자를 추가하는 데 문제가 있습니다 ... 다음 예제 코드를 수행했습니다 ... 입력 할 때 문자, 그것은 ??(및)로 자동 완성 문자

또 다른 의심, 내가 할 수있는 방법 프로그램이 자 ... 나는 다시 입력 할 때 추가 무시 .... 현재 커서 위치의 해당 문자를 추가하지 않습니다

Dictionary<char, char> glbin = new Dictionary<char, char> 
{ 
    {'(', ')'}, 
    {'{', '}'}, 
    {'[', ']'}, 
    {'<', '>'} 
}; 

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    int line = textBox1.GetLineFromCharIndex(textBox1.SelectionStart); 
    int column = textBox1.SelectionStart - textBox1.GetFirstCharIndexFromLine(line); 

    if(glbin.ContainsKey(e.KeyChar)) 
     textBox1.Text.Insert(column, glbin[e.KeyChar].ToString()); 
} 

답변

4

String은 변경할 수없는 개체이고 Insert Text on Text 속성은 아무 곳이나 할당되지 않은 문자열의 새 인스턴스를 만듭니다.

그리고 char을 무시하려면 KeyPressEventArgs Handled 속성을 true로 설정해야합니다 (닫는 문자의 역 사전이 필요합니다).

당신은 당신의 코드를 변경해야 : 물론 ....

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    int index = textBox1.SelectionStart; 
    if(glbin.ContainsKey(e.KeyChar)) 
    { 
     var txt = textBox1.Text; // insert both chars at once 
     textBox1.Text = txt.Insert(index, e.KeyChar + glbin[e.KeyChar].ToString()); 
     textBox1.Select(index + 1, 0);// position cursor inside brackets 
     e.Handled = true; 
    } 
    else if (glbin.Values.Contains(e.KeyChar)) 
    { 
     // move cursor forward ignoring typed char 
     textBox1.SelectionStart = textBox1.SelectionStart + 1; 
     e.Handled = true; 
    } 
} 
+0

오오오, 의도 한대로 코드가 다음 작동하고 있는지 xxxxxxxxxxx – Alexandre

+0

잘 모르겠어요. '(')을 입력하면 현재 커서 위치에'('를'첫 번째 문자와')로 삽입하고 커서 위치를 TextBox의 시작 부분으로 변경합니다 .. – Stijn

+0

정말 완벽하게 작동하지 않습니다 ... . 커서를 텍스트 상자의 시작 위치로 되 돌리십시오 ... – Alexandre