通过 VSTO 在 PowerPoint 设计器中捕获鼠标事件

2024-03-15

我正在使用 C# / VSTO 开发 PowerPoint (2013) 插件。当用户处于设计模式,而不是演示模式.

如何捕获与幻灯片上的形状/对象有关的鼠标事件,例如鼠标悬停、鼠标按下等?我想监听这些事件,以便创建位于对象/形状附近的自定义 UI。是否有任何我可以监听的事件,或者是否需要使用更高级的方法,例如创建全局鼠标监听器,将坐标转换为 PowerPoint 形状,并循环遍历幻灯片上的形状以查看鼠标是否在范围内任何形状的边界?我也将欣赏该问题的其他创造性解决方案。

我试图寻找答案,但没有运气。但是,我知道这是可能的,因为其他加载项正在执行我想要的操作。 Think-Cell 就是一个例子(https://www.youtube.com/watch?v=qsnciEZi5X0 https://www.youtube.com/watch?v=qsnciEZi5X0),其中您操作的对象是“普通”PowerPoint 对象,例如 TextFrame 和 Shapes。

我正在 Windows 8.1 Pro 上使用 .Net 4.5。


PowerPoint 不直接公开这些事件,但可以通过将全局鼠标挂钩与 PowerPoint 公开的形状参数相结合来实现您自己的事件。

这个答案涵盖了 MouseEnter 和 MouseLeave 的更困难的情况。要处理其他事件,例如 MouseDown 和 MouseUp,您可以使用提供的 PowerPoint 事件Application_WindowSelectionChange正如史蒂夫·林兹伯格提议的那样。

要获得全局鼠标钩子,您可以使用 ExcellentC# 中的应用程序和全局鼠标和键盘挂钩 .Net 库发现于http://globalmousekeyhook.codeplex.com/ http://globalmousekeyhook.codeplex.com/

您需要下载并引用该库,然后使用此代码设置鼠标挂钩

// Initialize the global mouse hook
_mouseHookManager = new MouseHookListener(new AppHooker());
_mouseHookManager.Enabled = true;

// Listen to the mouse move event
_mouseHookManager.MouseMove += MouseHookManager_MouseMove;

可以设置 MouseMove 事件来处理这样的鼠标事件(仅包含 MouseEnter 和 MouseLeave 的示例)

private List<PPShape> _shapesEntered = new List<PPShape>();       
private List<PPShape> _shapesOnSlide = new List<PPShape>();

void MouseHookManager_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
    // Temporary list holding active shapes (shapes with the mouse cursor within the shape)
    List<PPShape> activeShapes = new List<PPShape>();       

    // Loop through all shapes on the slide, and add active shapes to the list
    foreach (PPShapes in _shapesOnSlide)
    {
        if (MouseWithinShape(s, e))
        {
            activeShapes.Add(s);
        }
    }

    // Handle shape MouseEnter events
    // Select elements that are active but not currently in the shapesEntered list
    foreach (PPShape s in activeShapes)
    {
        if (!_shapesEntered.Contains(s))
        {
            // Raise your custom MouseEntered event
            s.OnMouseEntered();

            // Add the shape to the shapesEntered list
            _shapesEntered.Add(s);
        }
    }

    // Handle shape MouseLeave events
    // Remove elements that are in the shapes entered list, but no longer active
    HashSet<long> activeIds = new HashSet<long>(activeShapes.Select(s => s.Id));
    _shapesEntered.RemoveAll(s => {
        if (!activeIds.Contains(s.Id)) {
            // The mouse is no longer over the shape
            // Raise your custom MouseLeave event
            s.OnMouseLeave();

            // Remove the shape
            return true;
        }
        else
        {
            return false;
        }
    });
}

哪里的_shapesOnSlide是一个包含当前幻灯片上所有形状的列表,_shapesEntered是一个包含已输入但尚未离开的形状的列表,并且PPShape是 PowerPoint 形状的包装对象(如下所示)

MouseWithinShape 方法测试鼠标当前是否位于幻灯片上的形状内。它通过将形状的 X 和 Y 坐标(PowerPoint 以点为单位公开)转换为屏幕坐标,并测试鼠标是否位于该边界框内来实现此目的

/// <summary>
/// Test whether the mouse is within a shape
/// </summary>
/// <param name="shape">The shape to test</param>
/// <param name="e">MouseEventArgs</param>
/// <returns>TRUE if the mouse is within the bounding box of the shape; FALSE otherwise</returns>
private bool MouseWithinShape(PPShape shape, System.Windows.Forms.MouseEventArgs e)
{
    // Fetch the bounding box of the shape
    RectangleF shapeRect = shape.Rectangle;

    // Transform to screen pixels
    Rectangle shapeRectInScreenPixels = PointsToScreenPixels(shapeRect);

    // Test whether the mouse is within the bounding box
    return shapeRectInScreenPixels.Contains(e.Location);
}

/// <summary>
/// Transforms a RectangleF with PowerPoint points to a Rectangle with screen pixels
/// </summary>
/// <param name="shapeRectangle">The Rectangle in PowerPoint point-units</param>
/// <returns>A Rectangle in screen pixel units</returns>
private Rectangle PointsToScreenPixels(RectangleF shapeRectangle)
{
    // Transform the points to screen pixels
    int x1 = pointsToScreenPixelsX(shapeRectangle.X);
    int y1 = pointsToScreenPixelsY(shapeRectangle.Y);
    int x2 = pointsToScreenPixelsX(shapeRectangle.X + shapeRectangle.Width);
    int y2 = pointsToScreenPixelsY(shapeRectangle.Y + shapeRectangle.Height);

    // Expand the bounding box with a standard padding
    // NOTE: PowerPoint transforms the mouse cursor when entering shapes before it actually
    // enters the shape. To account for that, add this extra 'padding'
    // Testing reveals that the current value (in PowerPoint 2013) is 6px
    x1 -= 6;
    x2 += 6;
    y1 -= 6;
    y2 += 6;

    // Return the rectangle in screen pixel units
    return new Rectangle(x1, y1, x2-x1, y2-y1);

}

/// <summary>
/// Transforms a PowerPoint point to screen pixels (in X-direction)
/// </summary>
/// <param name="point">The value of point to transform in PowerPoint point-units</param>
/// <returns>The screen position in screen pixel units</returns>
private int pointsToScreenPixelsX(float point)
{
    // TODO Handle multiple windows
    // NOTE: PresStatic is a reference to the PowerPoint presentation object
    return PresStatic.Windows[1].PointsToScreenPixelsX(point);
}

/// <summary>
/// Transforms a PowerPoint point to screen pixels (in Y-direction)
/// </summary>
/// <param name="point">The value of point to transform in PowerPoint point-units</param>
/// <returns>The screen position in screen pixel units</returns>
private int pointsToScreenPixelsY(float point)
{
    // TODO Handle multiple windows
    // NOTE: PresStatic is a reference to the PowerPoint presentation object
    return PresStatic.Windows[1].PointsToScreenPixelsY(point);
}

最后我们实现一个自定义的PPShape暴露我们想要监听的事件的对象

using System.Drawing;
using Microsoft.Office.Interop.PowerPoint;
using System;

namespace PowerPointDynamicLink.PPObject
{
    class PPShape
    {
        #region Fields
        protected Shape shape;

        /// <summary>
        /// Get the PowerPoint Shape this object is based on
        /// </summary>
        public Shape Shape
        {
            get { return shape; }
        }

        protected long id;
        /// <summary>
        /// Get or set the Id of the Shape
        /// </summary>
        public long Id
        {
            get { return id; }
            set { id = value; }
        }

        protected string name;
        /// <summary>
        /// Get or set the name of the Shape
        /// </summary>
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        /// <summary>
        /// Gets the bounding box of the shape in PowerPoint Point-units
        /// </summary>
        public RectangleF Rectangle
        {
            get
            {
                RectangleF rect = new RectangleF
                {
                    X = shape.Left,
                    Y = shape.Top,
                    Width = shape.Width,
                    Height = shape.Height
                };

                return rect;
            }
        }
        #endregion

        #region Constructor
        /// <summary>
        /// Creates a new PPShape object
        /// </summary>
        /// <param name="shape">The PowerPoint shape this object is based on</param>
        public PPShape(Shape shape)
        {
            this.shape = shape;
            this.name = shape.Name;
            this.id = shape.Id;
        }
        #endregion

        #region Event handling
        #region MouseEntered
        /// <summary>
        /// An event that notifies listeners when the mouse has entered this shape
        /// </summary>
        public event EventHandler MouseEntered = delegate { };

        /// <summary>
        /// Raises an event telling listeners that the mouse has entered this shape
        /// </summary>
        internal void OnMouseEntered()
        {
            // Raise the event
            MouseEntered(this, new EventArgs());
        }
        #endregion

        #region MouseLeave
        /// <summary>
        /// An event that notifies listeners when the mouse has left this shape
        /// </summary>
        public event EventHandler MouseLeave = delegate { };

        /// <summary>
        /// Raises an event telling listeners that the mouse has left this shape
        /// </summary>
        internal void OnMouseLeave()
        {
            // Raise the event
            MouseLeave(this, new EventArgs());
        }
        #endregion
        #endregion
    }
}

为了完全详尽,有多个需要处理的额外元素此处未涵盖。这包括诸如在 PowerPoint 窗口停用时暂停鼠标挂钩、处理多个 PowerPoint 窗口和多个屏幕等。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 VSTO 在 PowerPoint 设计器中捕获鼠标事件 的相关文章

随机推荐