Saturday, October 11, 2008

Editor with Intellisense

Intellisense in .NET Windows Forms is a very desirable feature. Clients keep asking it.
I have tried to give a very basic implementation of intellisense in a rich text box control of .NET windows forms.

1. Take a Windows Form.
2. Add a rich text box called rtbText to it. This will serve as the main editor for us.
3. Add a Listbox call lbIntellisense to it. This will serve as the intellisense provider to us.

Now we have to handle the KeyPress event of the rtbText

private void rtbText_KeyPress(object sender, KeyPressEventArgs e)
{
if (Control.ModifierKeys == Keys.Control)
{
if (e.KeyChar == ' ')
{
e.Handled = true;
ShowIntellisense();
}
}
}

private void ShowIntellisense()
{
Point p = rtbText.GetPositionFromCharIndex(rtbText.SelectionStart);
p.Y = p.Y +rtbText.Font.Height + rtbText.Location.Y;
p.X = p.X+ rtbText.Location.X;
lbIntellisense.Location = p;
lbIntellisense.Visible = true;
lbIntellisense.SelectedIndex = 0;
lbIntellisense.Focus();
}


In the above method we are trying to see if Control Key is depressed and a space bar is pressed or not, if yes show the intellisense.

Now to add the intellisense text back to our editor we will handle the Leave event of the lbIntellisense

private void lbIntellisense_Leave(object sender, EventArgs e)
{
int cursorPostion = rtbText.SelectionStart;
if (lbIntellisense.Visible)
{
rtbText.Text = rtbText.Text.Insert(cursorPostion,
lbIntellisense.SelectedItem.ToString());
rtbText.SelectionStart = cursorPostion +
lbIntellisense.SelectedItem.ToString().Length;
lbIntellisense.Visible = false;
}
}


We check for visibility so that we may not end up adding the word twice. After adding the word we should also place the cursor at the appropriate place and we are done. See so simple right.
Well we can extend this to add more functionality as per our wishes.