C# CLI - UNO ブリッジから柔軟な Bootstrap

C# CLI-UNO ブリッジで uno.util.Bootstrap.bootstrap() すると自動的にランダムな名前の pipe が作成され、起動、接続されます。

OOo 起動時にコマンドラインオプションを与えたり、socket で接続したりといったときには次のようにします。

unoidl.com.sun.star.uno.XComponentContext xContext = null;

Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
        @"SOFTWARE\OpenOffice.org\UNO\InstallPath", false);
if (regkey == null)
    return;

string installPath = (string)regkey.GetValue("");
if (installPath == null)
    return;

string officePath = installPath + @"\soffice.exe";
string officeParams = " -nodefault -nologo -nofirststartwizard";
string unoParams = " -accept=pipe,name=officepipe1;urp;StarOffice.ServiceManager";

System.Environment.SetEnvironmentVariable(
    "URE_BOOTSTRAP", "vnd.sun.star.pathname:" + installPath + "/fundamental.ini");

System.Diagnostics.Process p = System.Diagnostics.Process.Start(officePath, officeParams + unoParams);

XComponentContext xLocalContext = uno.util.Bootstrap.defaultBootstrap_InitialComponentContext();
XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager();
XUnoUrlResolver xUrlResolver = (XUnoUrlResolver) xLocalServiceManager.createInstanceWithContext(
    "com.sun.star.bridge.UnoUrlResolver", xLocalContext);


int i = 0;
while (i < 20) {
    try
    {
        xContext = (XComponentContext)xUrlResolver.resolve(
            "uno:pipe,name=officepipe1;urp;StarOffice.ComponentContext");
        if (xContext != null)
            break;
    } catch (unoidl.com.sun.star.connection.NoConnectException) {
        System.Threading.Thread.Sleep(100);
    }
    i++;
}
if (xContext == null)
    return;

XMultiServiceFactory xMsf = (XMultiServiceFactory) xContext.getServiceManager();

Object desktop = xMsf.createInstance("com.sun.star.frame.Desktop");
XComponentLoader xLoader = (XComponentLoader)desktop;