Mouse wheel scrolling Toolstrip menu items

后端 未结 4 1408
梦如初夏
梦如初夏 2021-01-14 13:48

I have some menus that contain many menuitems. Mouse wheel doesn\'t scroll them. I have to use the keyboard arrows or click the arrows at top and bottom. Is it possible to u

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-14 13:54

    I modified Mohsen Afshin's answer to click the up/down arrows instead of sending up/down key presses. My application had a ContextMenuStrip called menu. Here's the code.

    In the initialization:

        menu.VisibleChanged += (s, e) =>
        {
            if (menu.Visible)
            {
                MouseWheel += ScrollMenu;
                menu.MouseWheel += ScrollMenu;
            }
            else
            {
                MouseWheel -= ScrollMenu;
                menu.MouseWheel -= ScrollMenu;
            }
        };
    

    The ScrollMenu function:

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
    
    private void ScrollMenu(object sender, MouseEventArgs e)
    {
        Point origin = Cursor.Position;
        int clicks;
    
        if (e.Delta < 0)
        {
            Cursor.Position = menu.PointToScreen(new Point(menu.DisplayRectangle.Left + 5, menu.DisplayRectangle.Bottom + 5));
            clicks = e.Delta / -40;
        }
        else
        {
            Cursor.Position = menu.PointToScreen(new Point(menu.DisplayRectangle.Left + 5, menu.DisplayRectangle.Top - 5));
            clicks = e.Delta / 40;
        }
    
        for (int i = 0; i < clicks; i++)
            mouse_event(0x0006, 0, 0, 0, 0);//Left mouse button up and down on cursor position
        Cursor.Position = origin;
    }
    

    I was having trouble getting the mouse_event function to click a specific location, so I moved the cursor, clicked, and then moved the cursor back. It doesn't seem the cleanest, but it works.

提交回复
热议问题