Revit Pick element from WinForm

2019-08-10 08:31发布

问题:

I'm trying to pick an object in Revit when clicking a button without closing the Form. the problem is when i click the button i can't interact with Revit.

here's the main code calling the Form and passing Revit as owner.

IWin32Window revit_window = new JtWindowHandle(ComponentManager.ApplicationWindow);
Process process = Process.GetCurrentProcess();
IntPtr h = process.MainWindowHandle;

form.ShowDialog(revit_window);

public class JtWindowHandle : IWin32Window
{
    IntPtr _hwnd;

    public JtWindowHandle(IntPtr h)
    {
        Debug.Assert(IntPtr.Zero != h, "expected non-null window handle");

        _hwnd = h;
    }

    public IntPtr Handle
    {
        get
        {
            return _hwnd;
        }
    }
}

and here is the Form code to select the element:

private void button1_Click(object sender, EventArgs e)
    {
        Hide();
        SelectionFilter1 selfilter1 = new SelectionFilter1();
        pickedRef1 = sel.PickObject(ObjectType.Element, selfilter1, "Select Family instance");
        Show();

    }

回答1:

Your Windows form is presumably not running as a modal form within a valid Revit API context.

Consequently, you are trying to access Revit and its API from outside. This is basically not possible. A workaround exists via the use of an external event.

This issue is currently also being discussed in the Revit API discussion forum thread on Revit API with WPF.

The official approach is presented in the Revit SDK sample ModelessDialog/ModelessForm_ExternalEvent.

Many other discussions and soutions are listed by The Building Coder in the topic group on Idling and External Events for Modeless Access and Driving Revit from Outside.