Passing a keyboard event to an other control

G

Guest

Hi,

I have a textbox and a listbox and I handle keydown events in the
textbox. I'd like to pass page up/down events to the listbox if the
focus is on the textbox, so that the default handler of the listbox
handles them.

That is I want to be able to scroll the listbox from the keyboard even
if current keyboard focus is on the textbox. How can I do that?

Thanks in advance.
 
M

Morten Wennevik

Hi,

I have a textbox and a listbox and I handle keydown events in the
textbox. I'd like to pass page up/down events to the listbox if the
focus is on the textbox, so that the default handler of the listbox
handles them.

That is I want to be able to scroll the listbox from the keyboard even
if current keyboard focus is on the textbox. How can I do that?

Thanks in advance.

Hi,

You can use the ListBox.TopIndex property to adjust the visible part. See
sample code below. The calculation of number of visible items can be
stored somewhere more appropriate as this is not likely to change during
the lifespan of the program.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.PageDown)
{
int n1 = listBox1.ItemHeight;
int n2 = listBox1.ClientRectangle.Height;
int num = n2 / n1;

if (listBox1.TopIndex + num > listBox1.Items.Count)
listBox1.TopIndex = listBox1.Items.Count - num;
else
listBox1.TopIndex += num;
}
else if (e.KeyCode == Keys.PageUp)
{
int n1 = listBox1.ItemHeight;
int n2 = listBox1.ClientRectangle.Height;
int num = n2 / n1;

if (listBox1.TopIndex - num < 0)
listBox1.TopIndex = 0;
else
listBox1.TopIndex -= num;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top