Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

visual studio - c# DataGridView detect MouseDown event on the scroll bar?

I have code that frequently updates the contents of my DataGridView, by clearing the previous contents, and then re-filling the entire DataGridView with new rows of data. But if I click and hold on the scroll bar, I would like for it to NOT update the DataGridView while I am scrolling.

1: How do I detect that I am currently holding down the mouse button in a scroll operation?

What I tested so far:

The DataGridView.MouseDown event does NOT fire if I click on the scroll bar. It only fires if I click on some content within the DataGridView, but it ignores clicks on the actual scroll bar itself. Curiously though, the MouseEnter event DOES fire when I hover the scroll bar. But I don't see how I can tell whether I am scrolling or not, just by detecting a hover. I need to detect the MouseDown event on the scroll bar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's the code:

    private void Form1_Load(object sender, EventArgs e)
    {
        PropertyInfo property = dataGridView1.GetType().GetProperty(
            "VerticalScrollBar", BindingFlags.NonPublic | BindingFlags.Instance);
        if (property != null)
        {
            ScrollBar scrollbar = (ScrollBar)property.GetValue(dataGridView1, null);
            scrollbar.MouseCaptureChanged += Scrollbar_MouseCaptureChanged;
            scrollbar.MouseLeave += Scrollbar_MouseLeave;
        }
    }

    static bool MouseIsDown = false;

    private void Scrollbar_MouseLeave(object sender, EventArgs e)
    {
        MouseIsDown = false;
    }

    private void Scrollbar_MouseCaptureChanged(object sender, EventArgs e)
    {
        MouseIsDown = !MouseIsDown;
    }

Then, simply check if MouseIsDown == true, and that'll tell you if the mouse is currently held down on the scroll bar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...