views:

287

answers:

1

Hi, I'd like to implement a ListView that will have a list of SelectedItems as it has now, but it will also have a separate item that is under cursor (movable with mouse/keyboard). Item selecting will be done with special action (for example the space key).

In other words, I'd like to suppress selection on the ListView and only change FocusedItem when selection would normally occur.

I think that I should do something with ListView's FocusedItem and SelectedItems properties, but the thing is that clicking an item selects it (also changes focus).

A solution would be to capture keydown and mouseclick events that can change selection and only change FocusedItem to the item according to the event (item under mouse pointer in mouseclick and item above/below current one in keydown up/down arrow). Then I would only add items to SelectedItems collection on my special event (space key press).

What I'm asking is if there is more ellegant approach to this problem or the solution above is as simple as it can be. Thanks

A: 

Ok, scratch this.

I needed to subclass ListView (ListViewEx);

handle keyboard selection events:

private void ListViewEx_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Down)
{
    //move focus down
    if (this.FocusedItem.Index + 1 < this.Items.Count)
    {
        this.FocusedItem = this.Items[this.FocusedItem.Index + 1];
        this.FocusedItem.EnsureVisible();
        e.Handled = true;
    }
}
else if (e.KeyData == Keys.Up)
{
    if (this.FocusedItem.Index - 1 < this.Items.Count)
    {
        this.FocusedItem = this.Items[this.FocusedItem.Index - 1];
        this.FocusedItem.EnsureVisible();
        e.Handled = true;
    }
}
}

and mouse events in WndProc

this way left click/keyboard up/down moves focus and keyboard right click makes selection

protected override void WndProc(ref Message m)
{
    const int WM_LBUTTONDOWN = 0x0201;
    const int WM_RBUTTONDOWN = 0x204;
    switch (m.Msg)
    {
        case WM_LBUTTONDOWN:
            Point pos = this.PointToClient(Cursor.Position);
            var item = GetItemAt(pos.X, pos.Y);
            this.FocusedItem = item;
            break;
        case WM_RBUTTONDOWN:
            pos = this.PointToClient(Cursor.Position);
            item = GetItemAt(pos.X, pos.Y);
            item.Selected = !item.Selected;
            break;
        default:
            base.WndProc(ref m);
            break;
    }
}
Axarydax
Some other things to consider: PageUp/PageDown also change selection; typing in the list also changes selection; focused item can be null.
Grammarian
also home/end, I'd also have to handle shift+home, shift+end, shift+up, shift+down, ctrl+click etc.
Axarydax