I need to call addDownload() method that is inside the main application class MainWindow.xaml.cs from App.xaml.cs
Some info about the Application:
In my App.xaml.cs i have code to run only one instance of the application. (Not my Code. I found it)
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using DownloadManager;
namespace DownloadManager
{
public partial class App : Application
{
private static readonly Semaphore singleInstanceWatcher;
private static readonly bool createdNew;
static App()
{
// Ensure other instances of this application are not running.
singleInstanceWatcher = new Semaphore(
0, // Initial count.
1, // Maximum count.
Assembly.GetExecutingAssembly().GetName().Name,
out createdNew);
if (createdNew)
{
// This thread created the kernel object so no other instance
// of this application must be running.
}
else
{
// This thread opened an existing kernel object with the same
// string name; another instance of this app must be running now.
// Gets a new System.Diagnostics.Process component and the
// associates it with currently active process.
Process current = Process.GetCurrentProcess();
foreach (Process process in
Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
NativeMethods.SetForegroundWindow(
process.MainWindowHandle);
NativeMethods.ShowWindow(process.MainWindowHandle,
WindowShowStyle.Restore);
break;
}
}
// Terminate this process and gives the underlying operating
// system the specified exit code.
Environment.Exit(-2);
}
}
private static class NativeMethods
{
[DllImport("user32.dll")]
internal static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd,
WindowShowStyle nCmdShow);
}
/// <summary>
/// Enumeration of the different ways of showing a window.</summary>
internal enum WindowShowStyle : uint
{
Hide = 0,
ShowNormal = 1,
ShowMinimized = 2,
ShowMaximized = 3,
Maximize = 3,
ShowNormalNoActivate = 4,
Show = 5,
Minimize = 6,
ShowMinNoActivate = 7,
ShowNoActivate = 8,
Restore = 9,
ShowDefault = 10,
ForceMinimized = 11
}
}
}
I need to pass Command Line Parameters to addDownload() method every time, whether the application is already running or not.
What i've tried so far:
First, i deleted the Startup entry point in App.xaml, so i can manage it inside code-behind
Then, if the Application is not running, create a new instance of MainWindow, and show it:
MainWindow MW = new MainWindow();
MW.Show();
Get Command Line Parameters, and pass it to the addDownload() method:
string[] args = Environment.GetCommandLineArgs();
if(args.Length > 1)
{
MW.addDownload(args[1]);
}
Ok, this part work perfectly.
But as i say, i need to pass Command Line Parameters also if the application is already running. Getting the command line parameters it's the same as before, but passing it to the addDownload() method of the current MainWindow instance, is not, and i have troubles to find a working way;
I tried:
try
{
var main = App.Current.MainWindow as MainWindow;
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
main.addDownload(args[1]);
}
}
catch(Exception ex)
{
MessageBox.Show(String.Format("{0}\n{1}", ex.GetType().ToString(), ex.Message));
}
But i get a NullReferenceException.. i think on the main declaration.. I don't know how to debug this particular situation inside Visual Studio.
Any help? What i'm doing wrong?
You get a NullReferenceException because you are wanting to access an instance of an object (MainWindow) that exists in a different process, and you can't do that. What you need to do is some sort of InterProcess communication, there are many ways to do this, one of which is to use .NET remoting (probably not the best way).
Here are a few links that turned up with a quick search:
http://www.codeproject.com/Articles/17606/NET-Interprocess-Communication
What is the best choice for .NET inter-process communication?
http://msdn.microsoft.com/en-us/library/kwdt6w2k(v=vs.100).aspx
Related
I have a windows forms tool in VB that i have been working on for a while now.
Now i would like to be able to access all of the controls and return values through the command prompt so that i am able to play with it through Azure and basically make the application a black box.
So this is how i went about thinking i should do it.
1 - In my project, i created a second solution, a C# Windows Command line framework.
2 - i than added the following script to that second project in order to run the win forms
using EnabledTest;
using System;
using System.Windows.Forms;
namespace Command_lineStartup
{
internal class Program
{
private static frmMain MainForm;
[STAThread]
private static void Main(string[] args)
{
if (args.Length > 0)
{
// Command line given, display console
}
else
{
AllocConsole();
ConsoleMain(args);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(MainForm = new frmMain());
GUI();
}
}
private static void ConsoleMain(string[] args)
{
Console.WriteLine("Command line = {0}", Environment.CommandLine);
for (int ix = 0; ix < args.Length; ++ix)
Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
// Console.ReadLine();
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
public static void GUI()
{
Console.WriteLine("Testing version 1 :");
Console.WriteLine("Enter Project File path to open, Project must be a .mmp file");
string Path = Console.ReadLine();
MainForm.LoadProject(Path);
}
}
}
However, I do not think this is the right way. When i run the console application through CMD using C:\TFS\Enabled Test\Command-lineStartup\bin\Debug\Command-lineStartup.exe"
I does not behave how i want it to work.
So my question is.
Am i going about this the right way? if so what am i doing wrong here
is there an easier way?
So i found a way in the end. When running the application through CMD, the arguments that are supplied can be accessed using
Dim cla As String() = Environment.GetCommandLineArgs()
then for each of the arguments provided u can do something with it.
For example,
If cla.Length > 1 Then
'cla(0) is the executable path.
'cla(1) is the Path to the project
If Not IsIDE() Then WCLicenseIsLicensed("Application", True)
Me.Text = Application.ProductName
mblnLoaded = True
LoadProject(cla(1))
TreeVieuwSystem.Nodes(cla(2)).Expand()
TreeVieuwSystem.SelectedNode = TreeVieuwSystem.Nodes(cla(2)).Nodes.Find(cla(2) & "\" & cla(3), True).First
NodeSelected()
If cla(2) = "Test Plans" Then
TheWindowThatAllowsYouToEditTheObject.RunTestPlan()
ElseIf cla(2) = "Tests" Then
TheWindowThatAllowsYouToEditTheObject.RunTest(False)
End If
Else
I have an application that is both gui and console.
Console: It executes from a windows schedule to do some automated tasks, so its called with an argument
GUI: Used for entering config parameters, a much nicer way for the user to do this than console.
All this works great. its primarily a console app, the console is hidden if its opened with no arguments and the configuration form is shown.
Problem:
If I open it FROM the console with NO arguments, the console is hidden and the form is shown.
how can i detect what or where i opened the app from, if it was opened from windows then hide the console, if it was opened from console then leave the console shown.
If you really want to know "where" your application has been started you have to know what is your parent process. In order to know your parent process you can read the solution of How to get parent process in .NET in managed way
Then you can for example check if your parent process name is explorer(windows) to open your application as a GUI.
sample code based on the solution provided in How to get parent process in .NET in managed way
namespace ConsoleApp1
{
public static class ProcessExtensions
{
private static string FindIndexedProcessName(int pid)
{
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;
for (var index = 0; index < processesByName.Length; index++)
{
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int)processId.NextValue() == pid)
{
return processIndexdName;
}
}
return processIndexdName;
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName)
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int)parentId.NextValue());
}
public static Process Parent(this Process process)
{
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Process.GetCurrentProcess().Parent().ProcessName);
Console.ReadKey();
}
}
}
This code will outputs:
debug in visual studio: devenv
start from windows: explorer
start from cmd: cmd
start from powershell console: powershell
...
One way to do this is to separate your cli version and gui version into 2 executable (like 7z do with 7z.exe a command line tool and 7zG the Gui version)
You could have 3 projects in visual studio:
MyApp.Console (console app)
MyApp.WindowsGui (winform/wpf app)
MyApp.Logic (all the logic)
Console and WindowsGui have a reference to your Logic project
This will give you cleaner code as each "Frontend" project will handle only their purpose (handling GUI or console stuff) and your Logic are callable by both frontends
I am unclear as to what you're trying to achieve. From my understanding, the application will launch as a console application regardless of having arguments or not. To prevent it from disappearing, you can utilize a Boolean to prevent the window from closing while the user is inputting configuration. For example (syntax may not be 100% at DialogResult):
using System;
using System.Windows.Forms;
// Allows you to access the static objects of Console
// without having to repeatedly type Console.Something.
using static System.Console;
static bool configured = false;
static bool showForm = false;
static void Main(string[] args) {
showForm = args.Length < 1;
if (showForm) {
WriteLine("The application needs to be configured.");
using (ConfigForm config = new ConfigForm()) {
if (config.ShowDialog() == DialogResult.OK) {
showForm = false;
configured = true;
// Set your configured arguments here.
}
}
}
// Prevents the console from closing.
while (showForm)
ReadKey();
// Do your processing in this condition.
if (!showForm && configured)
WriteLine("Thanks for playing. Press any key to exit.");
else // Retry or exit in this one.
WriteLine("An error occurred. Press any key to exit.");
ReadKey();
}
If your application is set as a console application then it will launch the console window by default. Now, if you need to show and hide your console at different times, you can look into this post where the accepted answer provides a proper way to utilize Windows API to achieve this without having to perform some shady logic to find the window by title or identity.
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
var handle = GetConsoleWindow();
// Hide
ShowWindow(handle, SW_HIDE);
// Show
ShowWindow(handle, SW_SHOW);
If this doesn't solve what you need, feel free to be more thorough in your post and include some code to give more definition to your issue. I am unable to comment and ask questions so I gave a basic solution. If you have any questions, feel free to ask.
This might help:
using System;
using System.Diagnostics;
static class IsRanFromConsole
{
private static readonly string[] consoleNames = {
"cmd", "bash", "ash", "dash", "ksh", "zsh", "csh",
"tcsh", "ch", "eshell", "fish", "psh", "pwsh", "rc",
"sash", "scsh", "powershell", "tcc"
};
private static bool isCache = false;
private static bool isConsole;
public static bool IsConsole()
{
if (!isCache)
{
string parentProc = Process.GetCurrentProcess().Parent().ProcessName;
isConsole = Array.IndexOf(consoleNames, parentProc) > -1;
}
return isConsole;
}
}
Usage:
Console.WriteLine(IsRanFromConsole.IsConsole());
For the .Parent() function, you need to add this code.
Consider next situation. I have injected my managed dll into the process using EasyHook. EasyHook injects dll using separate AppDomain. Now I need a way to get notifications about creation of new AppDomain in the current process.
So the question is there a way do get notifications when a new AppDomain was created in the process?
There is no event or easy way to do it, there is a COM interrupt that allows you to get a list of app domains loaded but any events etc are all hidden from us on private interfaces.
There is two ways you could do this but both require you to actively seek the information i.e. there is no event to register too.
Using Performance Counters.
Using mscoree COM interrupt.
Both there options can complement each other but it depends what level of information you need.
Using Performance Counters
CLR has numerous performance counters available but the one we care about resides in the category ".Net CLR Loading" and it is the counter called "Total Appdomains".
Using the System.Diagnostics namespace you can get the number of app domains per instance/process running in you machine.
Like the code below:
PerformanceCounter toPopulate = new PerformanceCounter(".Net CLR Loading", "Total Appdomains", "ConsoleApplication2.vshost", true);
Console.WriteLine("App domains listed = {0}", toPopulate.NextValue().ToString());
(please note the example needs the application instance name if you create your own app make sure to change this)
You can wrap this on a loop and raise an even for your app when the number changes.
(Not elegant but there is no way around it at the moment)
Using mscoree COM interrupt
Further more if you want to List all the app domains in a process you need to make use the MSCOREE.TBL library which is a COM library used by the CLRHost.
You can find the library at C:\WINDOWS\Microsoft.NET\Framework\vXXXXXX\mscoree.tlb
using mscoree;
If you are using it on window 7 or above you must make sure that the embed assembly type in the reference properties is turned off as this assembly can not be embedded like that.
See further information on this stack post: Interop type cannot be embedded
See the code below to see how you can return and list all app domains in a process (this will return the actual AppDomain instances for each app domain).
The original stack post for this can be found here: List AppDomains in Process
public static List<AppDomain> GetAppDomains()
{
List<AppDomain> _IList = new List<AppDomain>();
IntPtr enumHandle = IntPtr.Zero;
CorRuntimeHostClass host = new mscoree.CorRuntimeHostClass();
try
{
host.EnumDomains(out enumHandle);
object domain = null;
while (true)
{
host.NextDomain(enumHandle, out domain);
if (domain == null) break;
AppDomain appDomain = (AppDomain)domain;
_IList.Add(appDomain);
}
return _IList;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
finally
{
host.CloseEnum(enumHandle);
Marshal.ReleaseComObject(host);
}
}
Now that you can see how many app domains exist in a process and list them let put that to the test.
Below is a fully working example using both techniques.
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Xps.Packaging;
using System.Runtime.InteropServices;
using mscoree;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication2
{
class AppDomainWorker
{
public void DoSomeWork()
{
while (true)
{
for (int i = 0; i < 1000; i++)
{
var hello = "hello world".GetHashCode();
}
Thread.Sleep(500);
}
}
}
class Program
{
[STAThread]
static void Main(string[] args)
{
PerformanceCounter toPopulate = new PerformanceCounter(".Net CLR Loading", "Total Appdomains", "ConsoleApplication2.vshost", true);
Console.WriteLine("App domains listed = {0}", toPopulate.NextValue().ToString());
for (int i = 0; i < 10; i++)
{
AppDomain domain = AppDomain.CreateDomain("App Domain " + i);
domain.DoCallBack(() => new Thread(new AppDomainWorker().DoSomeWork).Start());
Console.WriteLine("App domains listed = {0}", toPopulate.NextValue().ToString());
}
Console.WriteLine("List all app domains");
GetAppDomains().ForEach(a => {
Console.WriteLine(a.FriendlyName);
});
Console.WriteLine("running, press any key to stop");
Console.ReadKey();
}
public static List<AppDomain> GetAppDomains()
{
List<AppDomain> _IList = new List<AppDomain>();
IntPtr enumHandle = IntPtr.Zero;
CorRuntimeHostClass host = new mscoree.CorRuntimeHostClass();
try
{
host.EnumDomains(out enumHandle);
object domain = null;
while (true)
{
host.NextDomain(enumHandle, out domain);
if (domain == null) break;
AppDomain appDomain = (AppDomain)domain;
_IList.Add(appDomain);
}
return _IList;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
finally
{
host.CloseEnum(enumHandle);
Marshal.ReleaseComObject(host);
}
}
}
}
I hope this is helpful and if you need any further help let us know.
I wrote a program in c#
now I would like to know what is the proper way to prevent the program from starting if it is already running?
so if it is already running, and double-click on the program it will not start because it is already running.
I can do that, but I was thinking of a standard and proper way.
The recommended way to do this is with a system mutex.
bool createdNew;
using(var mutex = new System.Threading.Mutex(true, "MyAppName", out createdNew))
{
if (createdNew)
// first instance
Application.Run();
else
MessageBox.Show("There is already an instace running");
}
The first parameter to the Mutex ctor tells it to give create a system wide mutex for this thread. If the Mutex already exists it will return out false through the 3rd parameter.
Update
Where to put this?
I'd put this in program.cs. If you put it in form_load you'll need to keep the mutex for the life time of the application (have the mutex as a member on the form), and manually release it in the form unload.
The earlier you call this the better, before the other app opens DB connections etc. and before resources are put created for forms / controlls etc.
Quick way I did in one of the applications .. You can look at the list of running processes to see whether the current application is already running and not start the application again.
Process[] lprcTestApp = Process.GetProcessesByName("TestApplication");
if (lprcTestApp.Length > 0)
{
// The TestApplication is already running, don't run it again
}
I think enumerating the process list could potentially be slow. You could also create a Mutex using the System.Threading.Mutex class and check to see if it's already created when the process starts. However, this would require calling into Win32 system code so wouldn't be completely platform agnostic.
Take a look at Scotts blog post and don't be foolished by the assembly name. It's just a file name of a standard file in the .Net framework.
Here are more informations direct out of MSDN for the WindowsFormsApplicationBase.
You can use a system-wide Semaphore, using the Semaphore Constructor (Int32, Int32, String, Boolean%) constructor and a fairly unique name.
Cheers, Matthias
If your application produces/consumes files, then you're better registering a system wide communication mechanism (e.g. a remoting or WCF endpoint, or even a socket). Then, if the second instance of the application is being launched from double clicking one of your files, you can send the file information across to the running instance.
Otherwise, if it's a standalone program, then as others have said, a Mutex or Semaphore would server equally well.
solution in Windows form application Prohibit again run application(reopen application).
1- first add Class RunAlready.cs
2-Call method processIsRunning() with Name Process from RunAlready.cs in Program.cs
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tirage.MainStand
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
PublicClass.Class.RunAlready RunAPP = new PublicClass.Class.RunAlready();
string outApp = RunAPP.processIsRunning("Tirage.MainStand");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainStand_FrmLogin fLogin = new MainStand_FrmLogin();
if (outApp.Length == 0)
{
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainStand_masterFrm());
}
}
else MessageBox.Show( "Instance already running");
}
}
}
class RunAlready:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PublicClass.Class
{
public class RunAlready
{
public string processIsRunning(string process)
{
string xdescription = "";
System.Diagnostics.Process[] processes =
System.Diagnostics.Process.GetProcessesByName(process);
foreach (System.Diagnostics.Process proc in processes)
{
var iddd = System.Diagnostics.Process.GetCurrentProcess().Id;
if (proc.Id != System.Diagnostics.Process.GetCurrentProcess().Id)
{
xdescription = "Application Run At time:" + proc.StartTime.ToString() + System.Environment.NewLine;
xdescription += "Current physical memory : " + proc.WorkingSet64.ToString() + System.Environment.NewLine;
xdescription += "Total processor time : " + proc.TotalProcessorTime.ToString() + System.Environment.NewLine;
xdescription += "Virtual memory size : " + proc.VirtualMemorySize64.ToString() + System.Environment.NewLine;
}
}
return xdescription;
}
}
}
How do you "Attach to Process..." for a console application thats running from a CMD window and not launched by F5? The reason I ask is because the application takes command line arguments and I want to have a genuine experience.
I've even attaching to CMD.exe, but no luck, or setting a break-point using Console.ReadKey() with also no luck. I'm kind of at a loss here.
Is this possible?
You have some options:
Use "Debug -> Command line arguments" option in Visual Studio;
Use "Debug -> Attach to process" and find your process; it is not cmd.exe, but a process with executable name like "MyProject.exe". You can use Process Explorer or another task manager with "tree view" support to easily find the Process ID - just look for the processes started by your cmd.exe.
On Windows (as of 2022), put Debugger.Launch() or Debugger.Break() into your code - with this executed, the system will launch a dialog asking you to choose what instance of Visual Studio to use for debugging (you can choose the one with your project already open).
To debug from the command line rather than using the VS GUI maze:
Launch the Visual Studio Command Prompt
type vsjitdebugger/? which gives you the command example like :
c:> vsjitdebugger [AppName] [Args] : Launch the specified executable and attach to debugger
typing tlist or tasklist will give you PIDs for attaching to existing processes. example:
c:> tasklist | find /i "web"
It's possible, sure. Try one of these two:
Start the process, then go to Debug->Attach and find the process. You may have to refresh to see it.
Add a "Debugger.Break()" statement in the code, if possible; that will break automatically (but be sure to remove it or surround it with preprocessor directives so it doesn't get into production code).
2020 UPDATE: to #VladV answer
Debugger.Break() doesn't work anymore.
Try using Debugger.Launch() instead, also put breakpoints after this line, or VS will start complaining.
As others have said, you can specify the stratup command line arguments from within the project and just start debugging within Visual Studio.
If you still want to attach to the running application, you need to attach the debugger to MyApp.exe (whatever your application is called - the exe that gets compiled to the bin\debug directory) and not cmd.exe. Attaching to cmd.exe it attaching to the command process, not the process of your application.
In the projects settings "Debug" section there's a textbox for "Command line arguments:". When the VS debugger starts the C# program, it'll pass those arguments to the process just as if the program had been started form the command line with those arguments.
The alternative is to use a command line debugger. There are a few options here, but in all honesty they're probably not what you want to use instead of VS unless you're getting into some really hairy debugging scenarios. If you're interested in checking them out, there's a good summary in this SO answer:
MSIL debuggers - Mdbg, Dbgclr, Cordbg
You can also try the techique of putting a call to System.Diagnostics.Debugger.Break() early in your initialization - if the program is running under a debugger, it'll break, it it's not running under a debugger you should be asked if you want to attach one. You can make the call conditionally depending on a configuration file or environment variable setting so you only get the break if you're really interested in it (somewhat intrusive, but not too bad).
Just add an registry entry for your exe's name in "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\currentversion\image file execution options", adding a "debugger" key valued with "vsjitdebugger.exe" under it, you can see a dialog pops up asking you to choose a VS version to debug when the exe starts up.
see MSDN "How to: Launch the Debugger Automatically" for more information.
I thought I would find some better solutions here but it seem the one I already have is the best. Debugger.Break() just simply don't work for me at all. But some time ago I found VisualStudioAttacher class on GitHub. Can't find the rep right now, but I'm posting my slightly modified version.
You will use it like this.
class Program {
static void Main(string[] args) {
VSAttacher.attachDebugger("SolutionFileContainingThisCode.sln");
Console.WriteLine("Hello World"); //set a brakepoint here
//...
}
}
This will just attach to currently opened instance of visual studio and it doesn't require you to choose the debugger.
Setup
Create new class library project named VSAttacher, or whatever you like.
Add reference to VSAttacher project in the project you want to debug.
In VSAttacher project, add reference to envdte library
Paste following code to VSAttacher project :
code:
using System.IO;
using EnvDTE;
using DTEProcess = EnvDTE.Process;
using System;
using System.Collections.Generic;
using Process = System.Diagnostics.Process;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
namespace AppController {
#region Classes
/// <summary>Visual Studio attacher.</summary>
public static class VSAttacher {
public static Action<object> log = (o) => Console.WriteLine(o);
//Change following variables depending on your version of visual studio
//public static string VSProcessName = "WDExpress";
//public static string VSObjectName = "!WDExpress";
public static string VSProcessName = "devenv";
public static string VSObjectName = "!VisualStudio";
/// <summary>
/// Tries to attach the program to Visual Studio debugger.
/// Returns true is the attaching was successful, false is debugger attaching failed.
/// </summary>
/// <param name="sln">Solution file containing code to be debugged.</param>
public static bool attachDebugger(string sln) {
if (System.Diagnostics.Debugger.IsAttached) return true;
log("Attaching to Visual Studio debugger...");
var proc = VSAttacher.GetVisualStudioForSolutions(
new List<string>() { Path.GetFileName(sln) });
if (proc != null) VSAttacher.AttachVSToProcess(
proc, Process.GetCurrentProcess());
else {
try { System.Diagnostics.Debugger.Launch(); }
catch (Exception e) { }
} // try and attach the old fashioned way
if (System.Diagnostics.Debugger.IsAttached) {
log(#"The builder was attached successfully. Further messages will displayed in ""Debug"" output of ""Output"" window.");
return true;
}
log("Could not attach to visual studio instance.");
return false;
}
#region Public Methods
#region Imports
[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow);
/// <summary>Returns a pointer to an implementation of <see cref="IBindCtx"/> (a bind context object). This object stores information about a particular moniker-binding operation.</summary>
/// <param name="reserved">This parameter is reserved and must be 0.</param>
/// <param name="ppbc">Address of an <see cref="IBindCtx"/>* pointer variable that receives the interface pointer to the new bind context object. When the function is successful, the caller is responsible for calling Release on the bind context. A NULL value for the bind context indicates that an error occurred.</param>
/// <returns></returns>
[DllImport("ole32.dll")]
public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc);
/// <summary>Returns a pointer to the <see cref="IRunningObjectTable"/> interface on the local running object table (ROT).</summary>
/// <param name="reserved">This parameter is reserved and must be 0.</param>
/// <param name="prot">The address of an IRunningObjectTable* pointer variable that receives the interface pointer to the local ROT. When the function is successful, the caller is responsible for calling Release on the interface pointer. If an error occurs, *pprot is undefined.</param>
/// <returns>his function can return the standard return values E_UNEXPECTED and S_OK.</returns>
[DllImport("ole32.dll")]
public static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SetFocus(IntPtr hWnd);
#endregion
public static string GetSolutionForVisualStudio(Process visualStudioProcess) {
var vsi = getVSInstance(visualStudioProcess.Id);
try { return vsi?.Solution.FullName;}
catch (Exception) {} return null;
}
public static Process GetAttachedVisualStudio(Process ap) {
var vsps = getVSProcess();
foreach (Process vsp in vsps) {
var vsi = getVSInstance(vsp.Id);
if (vsi == null) continue;
try {
foreach (Process dp in vsi.Debugger.DebuggedProcesses)
if (dp.Id == ap.Id) return dp;
} catch (Exception) {}
}
return null;
}
public static void AttachVSToProcess(Process vsp, Process applicationProcess) {
var vsi = getVSInstance(vsp.Id);
if (vsi == null) return;
//Find the process you want the VS instance to attach to...
DTEProcess tp = vsi.Debugger.LocalProcesses.Cast<DTEProcess>().FirstOrDefault(process => process.ProcessID == applicationProcess.Id);
//Attach to the process.
if (tp != null) {
tp.Attach();
ShowWindow((int)vsp.MainWindowHandle, 3);
SetForegroundWindow(vsp.MainWindowHandle);
} else {
throw new InvalidOperationException("Visual Studio process cannot find specified application '" + applicationProcess.Id + "'");
}
}
public static Process GetVisualStudioForSolutions(List<string> sns) {
foreach (string sn in sns) {
var vsp = GetVSProc(sn);
if (vsp != null) return vsp;
}
return null;
}
public static Process GetVSProc(string name) {
var vsps = getVSProcess(); var e = false;
foreach (Process vsp in vsps) {
_DTE vsi = getVSInstance(vsp.Id);
if (vsi == null) { e = true; continue; }
try {
string sn = Path.GetFileName(vsi.Solution.FullName);
if (string.Compare(sn, name, StringComparison.InvariantCultureIgnoreCase)
== 0) return vsp;
} catch (Exception) { e = true; }
}
if (!e) log($#"No running Visual Studio process named ""{VSProcessName}"" were found.");
return null;
}
#endregion
#region Private Methods
private static IEnumerable<Process> getVSProcess() {
Process[] ps = Process.GetProcesses();
//var vsp = ps.Where(p => p.Id == 11576);
return ps.Where(o => o.ProcessName.Contains(VSProcessName));
}
private static _DTE getVSInstance(int processId) {
IntPtr numFetched = IntPtr.Zero;
IMoniker[] m = new IMoniker[1];
GetRunningObjectTable(0, out var rot);
rot.EnumRunning(out var ms); ms.Reset();
var rons = new List<string>();
while (ms.Next(1, m, numFetched) == 0) {
IBindCtx ctx;
CreateBindCtx(0, out ctx);
m[0].GetDisplayName(ctx, null, out var ron);
rons.Add(ron);
rot.GetObject(m[0], out var rov);
if (rov is _DTE && ron.StartsWith(VSObjectName)) {
int currentProcessId = int.Parse(ron.Split(':')[1]);
if (currentProcessId == processId) {
return (_DTE)rov;
}
}
}
log($#"No Visual Studio _DTE object was found with the name ""{VSObjectName}"" that resides in given process (PID:{processId}).");
log("The processes exposes following objects:");
foreach (var ron in rons) log(ron);
return null;
}
#endregion
}
#endregion
}
If you use express version of visual studio, you should change VSProcessName and VSObjectName (this was tested only with express and community versions).