Mono MSC C# compiler how to add assembly references - c#

So im trying to run a .NET C# script in mono , but i get errors of missing assemblies...
C:\Users\user\Documents\GitHub\callCsharp-fromCPP\CMonoTest\Mp3ToSpeech.cs(1,14): error CS0234: The type or namespace name `Speech' does not exist in the namespace `System'. Are you missing an assembly reference?
C:\Users\user\Documents\GitHub\callCsharp-fromCPP\CMonoTest\Mp3ToSpeech.cs(6,7): error CS0246: The type or namespace name `NAudio' could not be found. Are you missing an assembly reference?
C:\Users\user\Documents\GitHub\callCsharp-fromCPP\CMonoTest\SeleniumWebdriver.cs(1,7): error CS0246: The type or namespace name `OpenQA' could not be found. Are you missing an assembly reference?
...
here is my current C++ code
#include <windows.h>
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <cstdlib>
#include <string>
#include <iostream>
#include <sstream>
#include <direct.h>
#include <filesystem>
#pragma comment(lib, "mono-2.0-boehm.lib") // replaced from mono-2.0.lib
#pragma comment(lib, "mono-2.0-sgen.lib") // It is new with GC code library GC from Gnu Compilication
#pragma comment(lib , "MonoPosixHelper.lib")
std::string get_working_path()
{
char temp[260]; // max windows path length
return (_getcwd(temp, sizeof(temp)) ? std::string(temp) : std::string(""));
}
int main(int argc, char* argv[])
{
#pragma region Load and compile the script
std::string Mp3Path = std::filesystem::path(get_working_path()).parent_path().string() + R"(\CMonoTest\ChromeDriverInstaller.cs )";
std::string ProgramPath = std::filesystem::path(get_working_path()).parent_path().string() + R"(\CMonoTest\Program.cs )";
std::string ChromeInstPath = std::filesystem::path(get_working_path()).parent_path().string() + R"(\CMonoTest\Mp3ToSpeech.cs )";
std::string SeleniumWebPath = std::filesystem::path(get_working_path()).parent_path().string() + R"(\CMonoTest\SeleniumWebdriver.cs )";
//C:\Users\user\.nuget\packages\dotnetseleniumextras.waithelpers\3.11.0\lib\net45\SeleniumExtras.WaitHelpers.dll
//C:\Users\user\.nuget\packages\naudio\2.1.0\lib\net6.0\NAudio.dll
//C:\Users\user\.nuget\packages\selenium.support\4.4.0\lib\net5.0\WebDriver.Support.dll
//C:\Users\user\.nuget\packages\selenium.webdriver\4.4.0\lib\net5.0\WebDriver.dll
//C:\Users\user\.nuget\packages\system.speech\6.0.0\lib\net6.0\System.Speech.dll
std::string references = R"(-r:C:\Users\user\.nuget\packages\dotnetseleniumextras.waithelpers\3.11.0\lib\net45\SeleniumExtras.WaitHelpers.dll
-r:C:\Users\user\.nuget\packages\naudio\2.1.0\lib\net6.0\NAudio.dll -r:/C:\Users\user\.nuget\packages\selenium.support\4.4.0\lib\net5.0\WebDriver.Support.dll
-r:C:\Users\user\.nuget\packages\selenium.webdriver\4.4.0\lib\net5.0\WebDriver.dll -r:C:\Users\user\.nuget\packages\system.speech\6.0.0\lib\net6.0\System.Speech.dll)";
std::string command = "mcs " + ProgramPath + ChromeInstPath + SeleniumWebPath + Mp3Path + references + R"( -target:library)";
//Compile the script
std::string Command = std::string(R"(cd C:\Program Files (x86)\Mono\bin && )") + command;
system(Command.c_str());
#pragma endregion
#pragma region Init mono runtime
mono_set_dirs("C:\\Program Files (x86)\\Mono\\lib",
"C:\\Program Files (x86)\\Mono\\etc");
//Init a domain
MonoDomain* domain;
domain = mono_jit_init("MonoScriptTry");
if (!domain)
{
std::cout << "mono_jit_init failed" << std::endl;
system("pause");
return 1;
}
//Open a assembly in the domain
MonoAssembly* assembly;
std::string assemblyPath = std::filesystem::path(get_working_path()).parent_path().string() + R"(\CMonoTest\Program.dll)";
assembly = mono_domain_assembly_open(domain, assemblyPath.c_str());
if (!assembly)
{
std::cout << "mono_domain_assembly_open failed" << std::endl;
system("pause");
return 1;
}
//Get a image from the assembly
MonoImage* image;
image = mono_assembly_get_image(assembly);
if (!image)
{
std::cout << "mono_assembly_get_image failed" << std::endl;
system("pause");
return 1;
}
#pragma endregion
#pragma region Run a static method
{
//Build a method description object
MonoMethodDesc* TypeMethodDesc;
const char* TypeMethodDescStr = "Program:StartWebRegister()";
TypeMethodDesc = mono_method_desc_new(TypeMethodDescStr, NULL);
if (!TypeMethodDesc)
{
std::cout << "mono_method_desc_new failed" << std::endl;
system("pause");
return 1;
}
//Search the method in the image
MonoMethod* method;
method = mono_method_desc_search_in_image(TypeMethodDesc, image);
if (!method)
{
std::cout << "mono_method_desc_search_in_image failed" << std::endl;
system("pause");
return 1;
}
//run the method
std::cout << "Running the static method: " << TypeMethodDescStr << std::endl;
mono_runtime_invoke(method, nullptr, nullptr, nullptr);
}
#pragma endregion
#pragma endregion
system("pause");
return 0;
}
Im trying to reference assemblies using -r: , using full path where they are located , but it doesnt work and i still get errors.
I Tried using msbuild , to build .csproj with instead of msc (see my other question Embedding mono in C++ , Could not load file or assembly 'System.Runtime' or one of its dependencies) but it cant call the static method
So my question is how can i reference the assemblies. Is there a easy way to do that in mono if you are using nuget? I saw on the docs that you can call packages using -pkg: if they have a .pc file (which none of .nuget have)

For those who have also problems with this , my problem was that
std::string references = R"(-r:C:\Users\user\.nuget\packages\dotnetseleniumextras.waithelpers\3.11.0\lib\net45\SeleniumExtras.WaitHelpers.dll
-r:C:\Users\user\.nuget\packages\naudio\2.1.0\lib\net6.0\NAudio.dll -r:C:\Users\user\.nuget\packages\selenium.support\4.4.0\lib\net5.0\WebDriver.Support.dll
-r:C:\Users\user\.nuget\packages\selenium.webdriver\4.4.0\lib\net5.0\WebDriver.dll -r:C:\Users\user\.nuget\packages\system.speech\6.0.0\lib\net6.0\System.Speech.dll)";
wasnt respecting this format
msc -r:"reference\to\assembly.dll"
it should be in quotes even if the path doesnt have any spaces.
This is a problem only when you want to use full path , as
msc -r:System.Assembly.dll
works fine!

Related

Embedding mono in C++ , Could not load file or assembly 'System.Runtime' or one of its dependencies

So im trying to embed C# mono in C++ i expect the msbuild to work fine(as it does now) and instead of an exception , i should get the text "Bark!!!" in the console , but i get Unhandled exception at 0x75FFEDDB (ucrtbase.dll) in CppMonoTest.exe: Fatal program exit requested. (at line comment in code) and * Assertion at ..\mono\metadata\class.c:3355, condition `is_ok (error)' not met, function:mono_class_try_load_from_name, Could not load runtime critical type Main.Program, due to Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
#include <windows.h>
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include <cstdlib>
#include <string>
#include <iostream>
#include <sstream>
#include <direct.h>
#include <filesystem>
#pragma comment(lib, "mono-2.0-boehm.lib") // replaced from mono-2.0.lib
#pragma comment(lib, "mono-2.0-sgen.lib") // It is new with GC code library GC from Gnu Compilication
#pragma comment(lib , "MonoPosixHelper.lib")
std::string get_working_path()
{
char temp[260]; // max windows path length
return (_getcwd(temp, sizeof(temp)) ? std::string(temp) : std::string(""));
}
int main(int argc, char* argv[])
{
#pragma region Load and compile the script
//Compile the script
std::string Command = std::string("cd ") +
std::filesystem::path(get_working_path()).parent_path().string() + R"(\CMonoTest && msbuild)";
system(Command.c_str());
#pragma endregion
#pragma region Init mono runtime
mono_set_dirs("C:\\Program Files (x86)\\Mono\\lib",
"C:\\Program Files (x86)\\Mono\\etc");
//Init a domain
MonoDomain* domain;
domain = mono_jit_init("MonoScriptTry");
if (!domain)
{
std::cout << "mono_jit_init failed" << std::endl;
system("pause");
return 1;
}
//Open a assembly in the domain
MonoAssembly* assembly;
std::string assemblyPath = std::filesystem::path(get_working_path()).parent_path().string()
+ R"(\CMonoTest\bin\Debug\net6.0\CMonoTest.dll)";
assembly = mono_domain_assembly_open(domain, assemblyPath.c_str());
if (!assembly)
{
std::cout << "mono_domain_assembly_open failed" << std::endl;
system("pause");
return 1;
}
//Get a image from the assembly
MonoImage* image;
image = mono_assembly_get_image(assembly);
if (!image)
{
std::cout << "mono_assembly_get_image failed" << std::endl;
system("pause");
return 1;
}
#pragma endregion
#pragma region Run a static method
{
//Build a method description object
MonoMethodDesc* TypeMethodDesc;
const char* TypeMethodDescStr = "Main.Program:StartWebRegister(string)";
TypeMethodDesc = mono_method_desc_new(TypeMethodDescStr, NULL);
if (!TypeMethodDesc)
{
std::cout << "mono_method_desc_new failed" << std::endl;
system("pause");
return 1;
}
//Search the method in the image
MonoMethod* method;
method = mono_method_desc_search_in_image(TypeMethodDesc, image); //----> Unhandled
//exception (ucrtbase.dll)
if (!method)
{
std::cout << "mono_method_desc_search_in_image failed" << std::endl;
system("pause");
return 1;
}
void* args[1];
std::string barkTimes = "Bark!!!";
args[0] = &barkTimes;
//run the method
std::cout << "Running the static method: " << TypeMethodDescStr << std::endl;
mono_runtime_invoke(method, nullptr, args, nullptr);
}
#pragma endregion
return 0;
}
this is the C++ code and a small script example in C#
namespace Main
{
class Program
{
static public int StartWebRegister(string email)
{
Console.WriteLine(email);
return 0;
}
}
}
I installed mono x86 at C:\Program Files (x86)\Mono , and my build config is x86 debug and i use msbuild to build the code as xbuild is deprecated ( note: i used msc and it worked fine , but i need to use some packages from nuget , and building from msbuild is easier as you need just the .csproj)...
So is there something im doing wrong or mono is not compatibile with msbuild assemblies?
___ 1. I checked the .mono lib folder for System.Runtime and it has it in there ...
___ 2. Could not load assembly System when using C++ and embedded mono to call to C# DLL
checked this but i have the path right as mono_set_dirs("C:\Program Files (x86)\Mono\lib", "C:\Program Files (x86)\Mono\etc");
___ 3. downgraded system.runtime from 4.3.1 to 4.0.0 in nuget manager in vs and the same (as in https://stackoverflow.com/a/54568734/16785067)
How do i fix these errors? If msbuild is not compatibile with mono , how do i add nuget packages to msc?
Note: packages im trying to use (from .csproj after downgrading system.runtime)
<ItemGroup>
<PackageReference Include="DotNetSeleniumExtras.WaitHelpers" Version="3.11.0" />
<PackageReference Include="NAudio" Version="2.1.0" />
<PackageReference Include="Selenium.Chrome.WebDriver" Version="85.0.0" />
<PackageReference Include="Selenium.Support" Version="4.4.0" />
<PackageReference Include="Selenium.WebDriver" Version="4.4.0" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="104.0.5112.7900" />
<PackageReference Include="System.Runtime" Version="4.0.0" />
<PackageReference Include="System.Speech" Version="6.0.0" />
</ItemGroup>
Here is the full console log : https://pastebin.com/DXtZ1C2k
So the problem was that the legacy mono , from mono-project.com isnt compatibile with msbuild net6.0 and net5.0 as the modern .net is actually .net core ... so if you want to build it with msbuild and use mono you should use .net 4.8.1 or older... Else if you want to use modern .net check this example

Retrieve wchar_t* from C++ to C++/CLI to C#

I have the following C++ function from the MyCppLib.h file of a third party library:
int CppFunc(int Index, wchar_t* String, int StringLength);
where the maximum length of String is StringLength. String is returned by the function (out).
I am trying to wrap this in C++/CLI for use in C#. According to this page it looks like StringBuilder should be used to marshall wchar_t* back to C++/CLI.
So I believe the C++/CLI should look something like this:
#include "MyCppLib.h"
using namespace System;
using namespace System::Text;
namespace MyCppCliLib
{
int CppCliFunc(int Index, StringBuilder^ sB, int StringLength) {
return ::CppFunc(Index, ???, StringLength);
}
}
Now, how can I retrieve the wchar_t* from C++ back to StringBuilder^ ? I can't find a good example on the topic...
I believe the C# side would then looks like:
StringBuilder sB = new StringBuilder();
int x = CppCliFunc(2, sB, 4096);
EDITS:
Thanks to all the comments, I finally got something working, it looks like this (don't quote me on it, it's my first steps in C++/CLI):
#include "MyCppLib.h"
#include <string.h>
#include <stdlib.h>
using namespace System;
using namespace System::Text;
namespace MyCppCliLib
{
String^ CppCliFunc(int Index, int StringLength) {
String^ newString="";
wchar_t* wchar = (wchar_t*)calloc(StringLength, sizeof(wchar_t));
if (wchar != NULL) {
int errorInt = ::CppFunc(Index, wchar, StringLength);
newString = gcnew String(wchar);
if(errorInt != 0){
throw gcnew Exception("Error #" + errorInt.ToString());
}
}else{
throw gcnew Exception("Error wchar is null");
}
free(wchar);
return newString;
}
}

How could I convert this to c++

I've written c# code for a registry modifying application, but the problem is c# is easily reversible and obfuscators make the program look like malware. So my problem is that I can't find anything close to Registry.SetValue for c++. Any help is appreciated.
I've tried using a c# to c++ tool by tangible but it was bad and it didn't work as expected at all.
I've also tried RegSetValueEx but I think I used it incorrectly.
This is what I tried:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <Windows.h>
using namespace std;
int main()
{
HKEY key;
if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion"), &key) != ERROR_SUCCESS)
{
cout << "unable to open registry";
}
if (RegSetValueEx(key, TEXT("value_name"), 0, REG_SZ, (LPBYTE)"value_data", strlen("value_data")*sizeof(char)) != ERROR_SUCCESS)
{
RegCloseKey(key);
cout << "Unable to set registry value value_name";
}
else
{
cout << "value_name was set" << endl;
}
return 0;
}
Could someone explain what is value_name value_data and how to use it with an example as that is the main thing I'm confused with.
Your best bet is to use RegSetValueEx - all C++ wrappers for the registry are very thin wrappers around the simple C API.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <Windows.h>
#include <tchar.h>
using namespace std;
int main()
{
HKEY key;
RegOpenKey(HKEY_CLASSES_ROOT, TEXT(""), &key);
LPCTSTR value = TEXT("");
LPCTSTR data = TEXT("");
LONG setRes = RegSetValueEx(key, value, 0, REG_SZ, (LPBYTE)data, _tcslen(data) * sizeof(TCHAR));
RegCloseKey(key);
return 0;
}
this solved it

Return value of SHLoadIndirectString is an errorcode

Hi I've been trying to get name of the metro app with the acquired from AppManifest.xml of the respective app. Came to know that SHLoadIndirectString could be used for this purpose. On checking its functionality manually, I couldn't get the result resource. The code snippet goes as below.
#include <iostream>
using namespace std;
#include <Shlwapi.h>
int main(){
LPWSTR output = L"";
LPWSTR input = L"#{Microsoft.BingMaps_2.1.3230.2048_x64__8wekyb3d8bbwe?ms-resource://Microsoft.BingMaps/resources/AppDisplayName}";
int result = SHLoadIndirectString(input, output, sizeof(output), NULL );
cout<<output;
return 0;
}
The return value "result" is always a negative value(changes if I am changing the input string respective to app). Please guide me on my mistake. Thanks.
Got the right answer.
#include <iostream>
using namespace std;
#include <Shlwapi.h>
int main()
{
PWSTR output = (PWSTR) malloc(sizeof(WCHAR)*256);
PCWSTR input = L"#{C:\\Program Files\\WindowsApps\\Microsoft.BingMaps_2.1.3230.2048_x64__8wekyb3d8bbwe\\resources.pri?ms-resource://Microsoft.BingMaps/Resources/AppShortDisplayName}";
int result = SHLoadIndirectString(input, output, 256, NULL );
cout<<output;
return 0;
}

Open a URL in a new browser process

I need to open a URL in a new browser process. I need to be notified when that browser process quits. The code I'm currently using is the following:
Process browser = new Process();
browser.EnableRaisingEvents = true;
browser.StartInfo.Arguments = url;
browser.StartInfo.FileName = "iexplore";
browser.Exited += new EventHandler(browser_Exited);
browser.Start();
Clearly, this won't due because the "FileName" is fixed to iexplore, not the user's default web browser. How do I figure out what the user's default web browser is?
I'm running on Vista->forward. Though XP would be nice to support if possible.
A bit more context: I've created a very small stand-alone web server that serves some files off a local disk. At the end of starting up the server I want to start the browser. Once the user is done and closes the browser I'd like to quit the web server. The above code works perfectly, other than using only IE.
Thanks in advance!
Ok. I now have working C# code to do what I want. This will return the "command line" you should run to load the current default browser:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
namespace testDefaultBrowser
{
public enum ASSOCIATIONLEVEL
{
AL_MACHINE,
AL_EFFECTIVE,
AL_USER,
};
public enum ASSOCIATIONTYPE
{
AT_FILEEXTENSION,
AT_URLPROTOCOL,
AT_STARTMENUCLIENT,
AT_MIMETYPE,
};
[Guid("4e530b0a-e611-4c77-a3ac-9031d022281b"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IApplicationAssociationRegistration
{
void QueryCurrentDefault([In, MarshalAs(UnmanagedType.LPWStr)] string pszQuery,
[In, MarshalAs(UnmanagedType.I4)] ASSOCIATIONTYPE atQueryType,
[In, MarshalAs(UnmanagedType.I4)] ASSOCIATIONLEVEL alQueryLevel,
[Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszAssociation);
void QueryAppIsDefault(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszQuery,
[In] ASSOCIATIONTYPE atQueryType,
[In] ASSOCIATIONLEVEL alQueryLevel,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName,
[Out] out bool pfDefault);
void QueryAppIsDefaultAll(
[In] ASSOCIATIONLEVEL alQueryLevel,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName,
[Out] out bool pfDefault);
void SetAppAsDefault(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszSet,
[In] ASSOCIATIONTYPE atSetType);
void SetAppAsDefaultAll(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName);
void ClearUserAssociations();
}
[ComImport, Guid("591209c7-767b-42b2-9fba-44ee4615f2c7")]//
class ApplicationAssociationRegistration
{
}
class Program
{
static void Main(string[] args)
{
IApplicationAssociationRegistration reg =
(IApplicationAssociationRegistration) new ApplicationAssociationRegistration();
string progID;
reg.QueryCurrentDefault(".txt",
ASSOCIATIONTYPE.AT_FILEEXTENSION,
ASSOCIATIONLEVEL.AL_EFFECTIVE,
out progID);
Console.WriteLine(progID);
reg.QueryCurrentDefault("http",
ASSOCIATIONTYPE.AT_URLPROTOCOL,
ASSOCIATIONLEVEL.AL_EFFECTIVE,
out progID);
Console.WriteLine(progID);
}
}
}
Whew! Thanks everyone for help in pushing me towards the right answer!
If you pass a path of the known file type to the (file) explorer application, it will 'do the right thing', e.g.
Process.Start("explorer.exe", #"\\path.to\filename.pdf");
and open the file in the PDF reader.
But if you try the same thing with a URL, e.g.
Process.Start("explorer.exe", #"http://www.stackoverflow.com/");
it fires up IE (which isn't the default browser on my machine).
I know doesn't answer the question, but I thought it was an interesting sidenote.
The way to determine the default browser is explained in this blog post:
http://ryanfarley.com/blog/archive/2004/05/16/649.aspx
From the blog post above:
private string getDefaultBrowser()
{
string browser = string.Empty;
RegistryKey key = null;
try
{
key = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//trim off quotes
browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
if (!browser.EndsWith("exe"))
{
//get rid of everything after the ".exe"
browser = browser.Substring(0, browser.LastIndexOf(".exe")+4);
}
}
finally
{
if (key != null) key.Close();
}
return browser;
}
Ok, I think I might have found it - IApplicationAssociationRegistration::QueryCurrentDefault [1]. According to the docs this is what is used by ShellExecute. I'll post code when I get it to work, but I'd be interested if others think this is the right thing to use (BTW, I'm Vista or greater for OS level).
[1]: http://msdn.microsoft.com/en-us/library/bb776336(VS.85).aspx QueryCurrentDefault
Ok. Been away on the conference circuit for a week, now getting back to this. I can do this with C++ now - and it even seems to behave properly! My attempts to translate this into C# (or .NET) have all failed however (Post On Question).
Here is the C++ code for others that stumble on this question:
#include "stdafx.h"
#include <iostream>
#include <shobjidl.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#include <atlbase.h>
#include <atlstr.h>
#include <AtlDef.h>
#include <AtlConv.h>
using namespace std;
using namespace ATL;
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = CoInitialize(NULL);
if (!SUCCEEDED(hr)) {
cout << "Failed to init COM instance" << endl;
cout << hr << endl;
}
IApplicationAssociationRegistration *pAAR;
hr = CoCreateInstance(CLSID_ApplicationAssociationRegistration,
NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistration),
(void**) &pAAR);
if (!SUCCEEDED(hr))
{
cout << "Failed to create COM object" << endl;
cout << hr << endl;
return 0;
}
LPWSTR progID;
//wchar_t *ttype = ".txt";
hr = pAAR->QueryCurrentDefault (L".txt", AT_FILEEXTENSION, AL_EFFECTIVE, &progID);
if (!SUCCEEDED(hr)) {
cout << "Failed to query default for .txt" << endl;
cout << hr << endl;
}
CW2A myprogID (progID);
cout << "Result is: " << static_cast<const char*>(myprogID) << endl;
/// Now for http
hr = pAAR->QueryCurrentDefault (L"http", AT_URLPROTOCOL, AL_EFFECTIVE, &progID);
if (!SUCCEEDED(hr)) {
cout << "Failed to query default for http" << endl;
cout << hr << endl;
}
CW2A myprogID1 (progID);
cout << "Result is: " << static_cast<const char*>(myprogID1) << endl;
return 0;
}
I will post the C# code when I finally get it working!
I've written this code for a project once... it keeps in mind any additional parameters set for the default browser. It was originally created to open HTML documentation in a browser, for the simple reason I always set my default program for HTML to an editor rather than a browser, and it annoys me to no end to see some program open its HTML readme in my text editor. Obviously, it works perfectly for URLs too.
/// <summary>
/// Opens a local file or url in the default web browser.
/// </summary>
/// <param name="path">Path of the local file or url</param>
public static void openInDefaultBrowser(String pathOrUrl)
{
pathOrUrl = "\"" + pathOrUrl.Trim('"') + "\"";
RegistryKey defBrowserKey = Registry.ClassesRoot.OpenSubKey(#"http\shell\open\command");
if (defBrowserKey != null && defBrowserKey.ValueCount > 0 && defBrowserKey.GetValue("") != null)
{
String defBrowser = (String)defBrowserKey.GetValue("");
if (defBrowser.Contains("%1"))
{
defBrowser = defBrowser.Replace("%1", pathOrUrl);
}
else
{
defBrowser += " " + pathOrUrl;
}
String defBrowserProcess;
String defBrowserArgs;
if (defBrowser[0] == '"')
{
defBrowserProcess = defBrowser.Substring(0, defBrowser.Substring(1).IndexOf('"') + 2).Trim();
defBrowserArgs = defBrowser.Substring(defBrowser.Substring(1).IndexOf('"') + 2).TrimStart();
}
else
{
defBrowserProcess = defBrowser.Substring(0, defBrowser.IndexOf(" ")).Trim();
defBrowserArgs = defBrowser.Substring(defBrowser.IndexOf(" ")).Trim();
}
if (new FileInfo(defBrowserProcess.Trim('"')).Exists)
Process.Start(defBrowserProcess, defBrowserArgs);
}
}
Short answer, you can't.
If the default browser is, say, Firefox, and the user already has a Firefox instance running, it will just be opened in another window or tab of the same firefox.exe process, and even after they close your page, the process won't exit until they close every window and tab. In this case, you would receive notification of the process exiting as soon as you started it, due to the temporary firefox.exe proc that would marshal the URL to the current process. (Assuming that's how Firefox's single instance management works).

Categories