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

标签 c# .net vsto powerpoint

我正在使用 C#/VSTO 为 PowerPoint (2013) 开发插件。当用户处于设计模式而非演示模式时,加载项将起作用。

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

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

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

最佳答案

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

这个答案涵盖了使用 MouseEnter 和 MouseLeave 的更困难的情况。要处理其他事件,例如 MouseDown 和 MouseUp,您可以使用提供的 PowerPoint 事件 Application_WindowSelectionChange,正如 Steve Rindsberg 所建议的那样。

要获得全局鼠标 Hook ,您可以使用出色的 Application and Global Mouse and Keyboard Hooks .Net Libary in C#,位于 http://globalmousekeyhook.codeplex.com/

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

// 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 窗口停用时暂停鼠标 Hook 、处理多个 PowerPoint 窗口和多个屏幕等。

关于c# - 通过 VSTO 在 PowerPoint 设计器中捕获鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22815084/

相关文章:

c# - 检查 JObject 中的空 JToken 或空 JToken

c# - 使用委托(delegate)发送字符串

c# - Blazor WASM Net 6 Preview 4 Azure AD - 尝试登录时出错 : 'Cannot read property ' toLowerCase' of undefined'

c# - 在虚拟方法上使用 OpCodes.Call 是否安全?

c# - 在 C# 中读取 .txt 文件的十六进制值

c# - 如何在应用程序内实现交互式教程?

c# - 如何结合 Reverse Poco Generator 使用 Effort

c# - 如何从 Roslyn 的 `BaseList` 中的接口(interface)中区分类?

c# - Outlook - 0×8004010F 访问安装的邮箱时抛出错误

excel - 为所有 Excel 版本构建加载项和 UDF