简体   繁体   中英

Prevent events from firing multiple times from single action

How can I prevent the firing of multiple events of the same kind triggered by a single action?

For example, I have a ListView containing some items. When I select or deselect all items, the SelectedIndexChanged event is fired once for each item. Rather, I would like to receive a single event indication the user's action (selection/deselection of items), regardless of the number of items.

Is there any way to achieve this?

You can't change the ListView code, and subclassing it doesn't provide many options.

I would suggest that you simply add a small delay (200ms or similar) to your code - ie you only do the calculation a little while after the last update. Something like:

using System;
using System.Windows.Forms;
static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        ListView list;
        TextBox txt;
        Timer tmr = new Timer();
        tmr.Interval = 200;
        Form form = new Form {
            Controls = {
                (txt = new TextBox { Dock = DockStyle.Fill, Multiline = true}),
                (list = new ListView { Dock = DockStyle.Right, View = View.List,
                   Items = { "abc", "def" , "ghi", "jkl", "mno" , "pqr"}})
            }
        };
        list.SelectedIndexChanged += delegate {
            tmr.Stop();
            tmr.Start();
        };
        tmr.Tick += delegate {
            tmr.Stop();
            txt.Text += "do work on " + list.SelectedItems.Count + " items"
                 + Environment.NewLine;
        };
        Application.Run(form);
    }
}

Only by by coming at the problem from a slightly different direction. Eg subscribe loss of focus.

In the end, the application or runtime cannot raise an event on "all selection changes done" without actually using something else because there is no way for the application to predict whether the user will perform another click on the control while it retains focus.

Even using focus, the user could switch back to that control.

If your ListView is in virtual mode , you could use the VirtualItemsSelectionRangeChanged event . This event will be fired only once for the user's action (selection/deseclection).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM