在Revit二次开发中,如果使用了非模态窗体,设置好参数输入后,点击按钮命令后,Revit没有立刻进入到激活状态,当前的窗体仍然是非模态窗体。以前我会在点击按钮中加入一句:this.Close(),直接关闭非模态窗体,这种方式太粗暴。
究其原因:在做的非模态窗体在执行相应命令后,窗体并没有关闭或是隐藏,就一直处于激活状态,导致Rveit不能立刻激活或者取到焦点。解决办法:使用WindowsAPI下的两个函数 GetActiveWindow(),SetActiveWindow(IntPtr hwnd),一个是获得当前系统获得焦点的窗体句柄,一个是设置当前系统某个窗体获得焦点。
为获得Rveit的窗体句柄,需要添加引用:AdWIndows.dll
简单使用:
public partial class TestForm : Form
{
private ExternalHandlerEventImp ex_Handler;
private ExternalEvent ex_Event;
public TestForm()
{
InitializeComponent();
ex_Handler = new ExternalHandlerEventImp();
ex_Event = ExternalEvent.Create(ex_Handler);
}
[DllImport("user32.dll")]
public static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
public static extern IntPtr SetActiveWindow(IntPtr hwnd);
IntPtr active = IntPtr.Zero;
private void EventForm_Load(object sender, EventArgs e)
{
active = Autodesk.Windows.ComponentManager.ApplicationWindow;
}
private void button1_Click(object sender, EventArgs e)
{
ex_Event.Raise();
SetActiveWindow(active);
}
}
public class ExternalHandlerEventImp : IExternalEventHandler
{
public void Execute(UIApplication app)
{
MessageBox.Show("Hello World");
}
public string GetName()
{
return "Test window reset";
}
}