Files
DotNet.Revit/DotNet.Revit.Hook/ElementMonitor.cs
2026-02-23 16:57:09 +08:00

140 lines
3.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Autodesk.Revit.UI;
using DotNet.Revit.Hook.Achieve;
using DotNet.Revit.Hook.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DotNet.Revit.Hook
{
/// <summary>
/// 元素监控.
/// </summary>
public class ElementMonitor
{
private static ElementMonitor m_Instance;
private MouseHook m_MouseHook;
private bool m_IsMonitor;
private UIApplication m_UIApplication;
private ElementMonitor(UIApplication uiApp)
{
m_Instance = this;
m_UIApplication = uiApp;
m_MouseHook = new MouseHook();
m_MouseHook.Install();
m_MouseHook.MouseDoubleClick += OnRaiseMouseDoubleClick;
}
/// <summary>
/// 静态实例可在入口类判断此实例是否为null防止重复注册.
/// </summary>
public static ElementMonitor Instance
{
get
{
return m_Instance;
}
}
/// <summary>
/// 是否监控.
/// </summary>
public bool IsMonitor
{
get
{
return m_IsMonitor;
}
set
{
m_IsMonitor = value;
}
}
/// <summary>
/// 当鼠标双击元素时触发此事件.
/// </summary>
public event HookHandler<DoubleClickElementEventArgs> DoubleClickElement;
/// <summary>
/// 注册元素监控,并指定是否立即监控.
/// </summary>
public static void Register(UIApplication uiApp)
{
if (uiApp == null)
{
throw new ArgumentNullException(nameof(uiApp));
}
new ElementMonitor(uiApp)
{
m_IsMonitor = true
};
}
/// <summary>
/// 注册元素监控,并指定是否立即监控.
/// </summary>
public static void Register(UIControlledApplication uiControllApp)
{
if (uiControllApp == null)
{
throw new ArgumentNullException(nameof(uiControllApp));
}
var flag = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod;
var uiApp = (UIApplication)uiControllApp.GetType().InvokeMember("getUIApplication", flag, Type.DefaultBinder, uiControllApp, null);
Register(uiApp);
}
/// <summary>
/// 返回1则拦截鼠标消息返回0则传递给真正消息接收者.
/// </summary>
private int OnRaiseMouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (this.DoubleClickElement == null)
{
return 0;
}
if (!m_IsMonitor || e.Button != MouseButtons.Left || e.Clicks != 2)
{
return 0;
}
var uiDoc = m_UIApplication.ActiveUIDocument;
if (uiDoc == null)
{
return 0;
}
var elemIds = uiDoc.Selection.GetElementIds();
if (elemIds.Count == 1)
{
var elem = uiDoc.Document.GetElement(elemIds.First());
if (elem == null)
{
return 0;
}
return this.DoubleClickElement(this, new DoubleClickElementEventArgs(elem));
}
return 0;
}
}
}