5

So what is happening is my console program opens up then runs external c# program/code from a text file. This all runs fine but when I close the original form window the program/code that it executed also closes. Is there a way to prevent the text file code I was running from closing?

This is the code its calling to run the program

static void MemExe(byte[] buffer)
        {
            Assembly asm = Assembly.Load(buffer);

            if (asm.EntryPoint == null)
                throw new ApplicationException("No entry point found!");

            MethodInfo ePoint = asm.EntryPoint;
            ePoint.Invoke(null, null);
        }

where the buffer is the code/program in bytes

and this is my main

static void Main(string[] args)
        {
            var data = File.ReadAllText(@"program.txt");
            MemExe(data);
        }
10
  • why don't you simply create a new process? msdn.microsoft.com/en-us/library/… – Benj Jun 19 '15 at 22:13
  • @Benj I cant do that as its running code from a text file, not a .exe program itself – jLynx Jun 19 '15 at 22:14
  • then the code is hosted in the executing process. as soon as the process is terminated, there is no frame to host/ run the code ... why do you need to terminate the host process? – Benj Jun 19 '15 at 22:17
  • Just create a service and do all your work from that – Icemanind Jun 19 '15 at 22:19
  • if you want the process to be invisible, then just create a Windows.Forms-Application and run ePoint.Invoke(null, null) in a non-background-thread. if you close the mainWindow your process should still be running (invisible) – Benj Jun 19 '15 at 22:22
1

A workaround would be to change the project's Output type in Project's Properties -> Application -> Output type from Console Application to Windows Application (see Screenshot)

How to Change from Console Application to Windows Application

This way no Console Window is created, so the the process will neither appear as two running processes nor can it be terminated by closing the Console Window.


This is the approach I would take. Your method is executed in a non-background-thread that prevents the process from terminating once the main-thread has terminated. However, you still cannot close the console window. That's why I would suggest switching to a Windows Application

using System;
using System.IO;
using System.Reflection;
using System.Threading;

namespace StackOverflow
{
    public static class Program
    {
        static void Main(string[] args)
        {
            RunExternalFunctionThread t = new RunExternalFunctionThread(File.ReadAllBytes(@"program.txt"));
            t.Run();
        }

        private class RunExternalFunctionThread
        {
            private Byte[] code;

            public RunExternalFunctionThread(Byte[] code)
            {
                this.code = code;
            }

            public void Run()
            {
                Thread t = new Thread(new ThreadStart(this.RunImpl));

                t.IsBackground = false;
                t.Priority = ThreadPriority.Normal;
                t.SetApartmentState(ApartmentState.STA);

                t.Start();
            }

            private void RunImpl()
            {
                Assembly asm = Assembly.Load(this.code);

                if (asm.EntryPoint == null) throw new ApplicationException("No entry point found!");

                MethodInfo ePoint = asm.EntryPoint;
                ePoint.Invoke(null, null);
            }
        }
    }
}
1
  • I think the idea is right with this answer but still, when I close the console window the program it executed from the txt file also closes – jLynx Jun 19 '15 at 22:48
3

I'm not going to get into the details of whether or not you should actually do what you want. At first it seems like a bad practice. But considering you have reasons to do this...

When your process closes, whatever it's executing halts automatically. In order to prevent this behavior, you have two options:

Option 1 - Running a second process

Instead of creating one C# project, you create two. The main one uses Process.Start to activate the second one. If the main one closes, the second one will remain executing until it finishes.

Option 2 - Disable the close button

If you don't mind to interact with native Windows code, thus preventing your code from executing in other environments which is now officially going to be supported with VS 2015, you can manually disable the close button from the CMD doing this:

        [DllImport("user32.dll")]
        static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
        [DllImport("user32.dll")]
        static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
        internal const UInt32 SC_CLOSE = 0xF060;
        internal const UInt32 MF_ENABLED = 0x00000000;
        internal const UInt32 MF_GRAYED = 0x00000001;
        internal const UInt32 MF_DISABLED = 0x00000002;
        internal const uint MF_BYCOMMAND = 0x00000000;


        static void Main(string[] args)
        {
            EnableCloseButton(this, false);
        }

        public static void EnableCloseButton(IWin32Window window, bool bEnabled)
        {
            IntPtr hSystemMenu = GetSystemMenu(window.Handle, false);
            EnableMenuItem(hSystemMenu, SC_CLOSE, (uint)(MF_ENABLED | (bEnabled ? MF_ENABLED : MF_GRAYED)));
        }

Reference: https://social.msdn.microsoft.com/forums/vstudio/en-us/545f1768-8038-4f7a-9177-060913d6872f/disable-close-button-in-console-application-in-c

4
  • I want to be able to close the console window once the program is running. But since the program I am running isn't an exe I cant use Process.Start as there is nothing to start. This is why im using my MemExe function and passing the code bytes through to it. As for your option 2 I want to be able to close that console window so that wouldn't necessarily work either – jLynx Jun 19 '15 at 22:22
  • 1
    @DarkN3ss I think he is saying have your main console application and then have a separate service application. Start the service application from your console application with Process.Start and then run the code file on start up of the service application. Thus, the code file doesn't end when your console application ends since it's frame is the service application. – Mark Balhoff Jun 19 '15 at 22:30
  • @MarkBalhoff Could you please provide an example, I'm finding it difficult to understand exactly what you are meaning? – jLynx Jun 19 '15 at 22:35
  • @DarkN3ss You run console application MainApp.exe. MainApp.exe calls Process.Start(); on the service application WorkerApp.exe. MainApp.exe can now close. `WorkerApp.exe proceeds to run the text file code invisible to the user. So move your code above from the main application to the worker application. The main application just calls the worker application. Or possibly write the whole thing as a service application if that is all the main application does. – Mark Balhoff Jun 19 '15 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.