SoFunction
Updated on 2025-05-13

C# implements an example of calling external applications through processes

Taking the WINFORM application as an example, call the PYTHON program (Matplotlib drawing graphic program) in the C# application, and embed the window program generated by calling the PYTHON program in the WINFORM window.

Window program class

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace MyForm
{
    public partial class Form2 : .Office2007Form
    {
        private static  log = (typeof(Form2));
        [DllImport("")]
        private static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, Int32 nShowCmd);
        private string pyFileName = @"";
        //After generating the file, you need to modify the parameter value to the absolute path of the generated file        private string pyParamsfilePath = @"";
        private string args = "-u";
        private string dataType = "";
        public delegate void UpdateUI();//Delegate is used to update the UI        Process p = null;//Receive python program process, used to control the process        Thread startload;//Thread is used for matplotlib form processing        IntPtr figure1;//Image handle        #region Drawing Events Windows API Call        [DllImport("")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("")]
        public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        [DllImport("", CharSet = )]
        public static extern int MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool BRePaint);

        const int GWL_STYLE = -16;
        //const int WS_CAPTION = 0x00C00000;
        const int WS_CAPTION = 0x00CC0000;
        const int WS_THICKFRAME = 0x00040000;
        const int WS_SYSMENU = 0X00080000;
        [DllImport("user32")]
        private static extern int GetWindowLong( hwnd, int nIndex);

        [DllImport("user32")]
        private static extern int SetWindowLong( hwnd, int index, int newLong);
        [DllImport("user32")]
        private static extern int InvalidateRect( hwnd, object rect, bool bErase);
        /// <summary>Maximize window, minimize window, normal size window        /// nCmdShow: 0 hide, 3 maximize, 6 minimize, 5 normal display        /// &lt;/summary&gt;
        [DllImport("", EntryPoint = "ShowWindow")]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
        #endregion
        /// &lt;summary&gt;
        /// Draw graphic button click event        /// &lt;/summary&gt;
        /// &lt;param name="sender"&gt;&lt;/param&gt;
        /// &lt;param name="e"&gt;&lt;/param&gt;
        private void Draw3D(object sender, EventArgs e)
        {
            Create3DChart("Z");
        }
        /// &lt;summary&gt;
        /// Create 3D graphics        /// &lt;/summary&gt;
        private void Create3DChart(string drawDataType)
        {
            if ( != null)
            {//If the python program process is not null                if (!)
                {//If the current process has not been terminated, the value is false when it is not terminated, and the value is true when it is terminated                    ();
                }

            }
            dataType = drawDataType;
            //Instantiate the thread, use it to call matlab for the first time, and put the image form into winform            startload = new Thread(new ThreadStart(RunPythonScript));
            //Start the thread            ();
        }
        /// &lt;summary&gt;
        /// End the process when closing the window        /// &lt;/summary&gt;
        /// &lt;param name="sender"&gt;&lt;/param&gt;
        /// &lt;param name="e"&gt;&lt;/param&gt;
        public void Close3DChart(object sender, FormClosedEventArgs e)
        {
            if ( != null)
            {//If the python program process is not null                if (!)
                {//If the current process has not been terminated, the value is false when it is not terminated, and the value is true when it is terminated                    ();
                }

            }
        }
        /// &lt;summary&gt;
        /// Call python script to draw 3D graphics        /// &lt;/summary&gt;
        public void RunPythonScript()
        {

            ($"Start drawing thread---{()}");
            int count50ms = 0;
            //Get the absolute path to python (put the file in c# This can be done in the debug folder of the program) string path = + pyFileName;            //Create a process            Process process = new Process();
            //If there is no environment variable configured, the absolute path that can be written. If it is configured, just write ""             = ;
            //Set python file path parameters            string sArguments = path;
            //Set execution mode parameters            sArguments += " " + dataType;
            sArguments += " " +  + "\\" + pyParamsfilePath;
            sArguments += " " + args;
            ($"Drawing parameters---{()}:{sArguments}");
             = sArguments;//Set command line argument             = true;//Set the creation process directly from the executable file            // = true;//Set the application output write process (program output can be displayed in c#Console) Used during debugging // = true;//Set the application input read process (program input can be read process input) Used during debugging            // = true;//Set the application error message writing process (program error output can be displayed in c#Console) Used during debugging = true;//Set the new window to start the process             = ;//Set window hidden startup
             = process;


            ();//The process starts
            //();//Use when reading data asynchronously            // += new DataReceivedEventHandler(process_OutputDataReceived); // Used during debugging
            figure1 = ;
            //Long loop to find the figure1 form            while (figure1 == )
            {
                //Look for the Figure 1 form of matplotlib. After installing the PYQT component, look for the class name Qt652QWindowIcon. The class name TkTopLevel is not installed.                figure1 = FindWindow("Qt652QWindowIcon", "Figure 1");

                //Delay 50ms                (50);
                count50ms++;
                //20s timeout setting                if (count50ms &gt;= 400)
                {
                    // = "The matplotlib resource loading time is too long!";                    return;
                }
            }

            //Cross-threaded, delegate execution            UpdateUI update = delegate
            {

                ShowWindow(figure1, 0);
                //Hide tag                // = false;
                //Set the parent form of the matlab image form to panel                SetParent(figure1, );
                //Get the original style of the form                var style = GetWindowLong(figure1, GWL_STYLE);
                //Set new style, remove the title, and cannot change the size through borders                SetWindowLong(figure1, GWL_STYLE, style &amp; ~WS_CAPTION &amp; ~WS_THICKFRAME);

                //Move to the appropriate position in the panel and repaint it                MoveWindow(figure1, 0, 0, , , true);
                //Calling the display form function, hiding and displaying is equivalent to refreshing the form
                ShowWindow(figure1, 5);
            };
            (update);
            //Move again to prevent errors from being displayed            (100);
            MoveWindow(figure1, 0, 0, , , true);


            //();//Waiting to exit        }
    }
}

Process information class

    /// &lt;summary&gt;
    /// Process information class    /// &lt;/summary&gt;
    public static class processInfo {
        public static Process process { get; set; } = null;
    }

System Settings

    /// &lt;summary&gt;
    /// System Settings Class    /// &lt;/summary&gt;
    public static class SystemConfigClass { 
        public static string PythonPath { get; set; } = @"D:\Python\";
        /// &lt;summary&gt;
        /// 
        /// &lt;/summary&gt;
        /// &lt;param name="dataFilePath&gt; + "\\"&lt;/param&gt;
        public static void SetSystemConfig(string dataFilePath) {
            if ((dataFilePath))
            { //If the file exists, save the file after deleting the file                string content = "";
                using (StreamReader dataFile = new StreamReader(dataFilePath))
                {
                    while ((content = ()) != null)
                    {
                        content = ();
                        var tempArr = ("^".ToCharArray()).ToList();
                        if (tempArr != null &amp;&amp;  == 2) {
                             = tempArr[1];
                        }
                        else {
                             = @"D:\Python\";
                        }
                    }
                    ();
                    ();
                };
            }
            
        }
    }

This is the end of this article about C#’s implementation example of calling external applications through processes. For more related content of C#’s process to call external applications, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!