Hi I'm having some headaches trying to find how to get the process of a parent application that starts my C# console app.

I've been trying a lot of things all day and come up short.

The most likely candidate was this, except it does not return what I expect and tackes abot 1000 ms to return.

static void Main(string[] args)
        {
            var pcs = Process.GetCurrentProcess();

            Console.WriteLine(pcs);
            Console.ReadLine();
        }

Also tried

static void Main(string[] args)
        {
            var pc = Process.GetProcessById(0);//.ProcessName);

            Console.WriteLine(pc);
            Console.ReadLine();
        }

And a number of other attempts.

Im after the string path, and or PID of the process that starts my app.

Anyone know how to achieve this?

Edit:
Heres how I've done it in C++

void pname(void)
   {
    	HMODULE module = GetModuleHandle(NULL);
	if(!module)
	{
		return;
	}

	TCHAR name[MAX_PATH] = { };
	if(GetModuleFileName(module, name, MAX_PATH) == 0)
	{
		return;
	}

	MessageBox(NULL,name,_T("name"),0);
   }

Cant edit.

Here is a meagre attempts to import the functions

[DllImport("kernel32.dll")]
        public static extern IntPtr GetModuleHandle(string lpModuleName);
        [DllImport("kernel32.dll")]
        public static extern string GetModuleFileName(IntPtr module, string name);
        static void Main(string[] args)
        {
            
            IntPtr m = GetModuleHandle(null);
            
            Console.WriteLine(m.ToString());
            Console.ReadLine();
        }

I'm getting what I think is the handle, but cannot properly import GetModuleFileName()

Sorry for the edit and reply, just trying to get as much info across as I can.

I have this now.

class Program
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetModuleHandle(string lpModuleName);
        [DllImport("kernel32.dll")]
        public static extern uint GetModuleFileName([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In] [MarshalAs(UnmanagedType.U4)] int nSize);

        static void Main(string[] args)
        {
            StringBuilder fileName = new StringBuilder(255);
            IntPtr m = GetModuleHandle(null);
            GetModuleFileName(m, fileName, fileName.Capacity);
            
            Console.WriteLine(m.ToString());
            Console.WriteLine(fileName.ToString());
            Console.ReadLine();
        }
    }

But just gives me the name of my C# app.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.