A simple code for an authorization detection program, C# implements program detection

Introduction

Implement a program detection in unity. When Unity is started, it will judge whether another program is started. If it is started, it will not be processed. If it is not started, unity will be closed.

  1. Determine whether the file name and file path to be judged are correct to avoid internal errors in the program
  2. Obtain all program names to determine whether the program to be detected is started
  3. Judging by the path, whether it is the program to be started, avoiding programs with the same name

Warning

The third one failed to be implemented correctly, and the reason has not been found for the time being. To try it out just uncomment the commented macro command.
The file needs to be two lines, the first line is the name of the file to be detected, and the second line is the path of the program to be detected, but because the function has not been realized, it can be right or wrong, but there must be.

To try a third place where you need to uncomment include

1.

//#if !UNITY_EDITOR
// Set_processExePath_Long(processInfoLines);
//#endif


2. //#if !UNITY_EDITOR
//bFilePath = System.AppDomain.CurrentDomain.BaseDirectory
// + Application.productName + "_Data"
// + "/StreamingAssets/"
// + processNamePath;

// txt.text = txt.text + "bFilePath_AppDomain:" + bFilePath + "\\
";

//lineCount = 0;
// using (StreamReader sr = new StreamReader(bFilePath))
// {
// while (sr. ReadLine() != null)
// {
//lineCount++;
// }
// }

// if (lineCount == 2)
// {
// return isGetCheckIfProcessInfo = true;
// }
//#endif

3.
//#if !UNITY_EDITOR
// SameNameCheck(processes);
//#endif


Code

using System;
using System. Collections;
using System.Collections.Generic;
using System. Diagnostics;
using System.IO;
using System. Linq;
using System.Runtime.InteropServices;
using Unity.VisualScripting;
using UnityEngine;
using Debug = UnityEngine. Debug;


public class NewBehaviourScript : MonoBehaviour
{
    [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern int MessageBox(IntPtr handle, string message, string title, int type, Action action = null);

    private string processNamePath = "B.txt";//The path of the name of the file that needs to be read
    private string processName = "";//Program name to be detected
    private string processExePath_Short = "";//The relative path of the name of the checked program,
    string processExePath_Long = "";//The absolute path of the program to be detected


    void Start()
    {
        if (!GetCheckIfProcessInfo())
        {
            MyQuiitMessageBox("Warning", "The program internal detection file configuration error, contact the administrator!_1");
            return;
        }

        string[] processInfoLines = new string[] {"","" };//used to store the read string
        using (StreamReader sr = new StreamReader(bFilePath))
        {
            int index = 0;
            string line = "";
            while ((line = sr. ReadLine()) != null)
            {
                processInfoLines[index] = line;
                index = index + 1;
            }
        }

        //If you add .exe to the file name, remove .exe and remove the space
        for (int i = 0; i < processInfoLines. Length; i ++ )
        {
            if (processInfoLines[i].EndsWith(".exe"))
            {
                processInfoLines[i] = processInfoLines[i].Replace(" ", "").Substring(0, processInfoLines[i].Length - 4);
            }
        }

        // process the string
        processName = processInfoLines[0];
        if (processName. StartsWith(@""))
        {
            processName = processName.Replace(@"", "");//Assignment after processing
        }

//#if !UNITY_EDITOR
// Set_processExePath_Long(processInfoLines);
//#endif


        InvokeRepeating(nameof(CheckIfProcessRunning), 3f, 5f);//The first delay is 3S, and then every 5s starts to detect the startup program
    }


    // judge the path
    private void Set_processExePath_Long(string[] lines)
    {
        processExePath_Short = lines[1];
        if (!processExePath_Short.StartsWith(@""))//Judge if it starts with ""
        {
            processExePath_Short = @"" + processExePath_Short;
        }
        if (!processExePath_Short.EndsWith(@"")) judge whether it is the end of "", error is allowed
        {
            processExePath_Short = processExePath_Short + @"";
        }

        processExePath_Long = System.AppDomain.CurrentDomain.BaseDirectory;//C:\Users\bin\Debug\
        processExePath_Long = processExePath_Long.Replace(processExePath_Short, "");
        processExePath_Long = processExePath_Long + @"" + processName + ".exe";//assignment

    }


    private string bFilePath = "";
    /// <summary>
    /// Obtain whether the information of the configuration file to be detected is correct
    /// First judge whether it is 1 row
    /// </summary>
    private bool GetCheckIfProcessInfo()
    {
        bool isGetCheckIfProcessInfo = false;//Have you read the information?

        if (processNamePath. StartsWith(@""))
        {
            processNamePath = processNamePath. Remove(0, 1);
        }

        bFilePath = Path.Combine(Application.streamingAssetsPath, processNamePath);//Assume the file to be read is under streamingAssets

        int lineCount = 0;//total number of lines
        using (StreamReader sr = new StreamReader(bFilePath))
        {
            while (sr. ReadLine() != null)
            {
                lineCount++;
            }
        }

        if (lineCount == 2)
        {
            return isGetCheckIfProcessInfo = true;
        }


//#if !UNITY_EDITOR
//bFilePath = System.AppDomain.CurrentDomain.BaseDirectory
// + Application.productName + "_Data"
// + "/StreamingAssets/"
// + processNamePath;

// txt.text = txt.text + "bFilePath_AppDomain:" + bFilePath + "\\
";

//lineCount = 0;
// using (StreamReader sr = new StreamReader(bFilePath))
// {
// while (sr. ReadLine() != null)
// {
//lineCount++;
// }
// }

// if (lineCount == 2)
// {
// return isGetCheckIfProcessInfo = true;
// }
//#endif

        return isGetCheckIfProcessInfo = false;
    }


    /// <summary>
    /// Detect startup program
    /// </summary>
    void CheckIfProcessRunning()
    {
        Process[] processes = Process. GetProcessesByName(processName);
        if (processes.Length == 0)//Not detected
        {
            Debug.Log("The program has not started");
            MyQuiitMessageBox("Warning", "Not detected" + processName + "Program starts, program exits_2");
        }
        else
        {
            //In general, the code in else can be deleted, here is because it is a fixed path, so it needs to be added
//#if !UNITY_EDITOR
// SameNameCheck(processes);
//#endif

        }

    }

    /// <summary>
    /// If it is the same name but the path is incorrect, it needs to be closed
    /// Is being used ah hey hey hey
    /// </summary>
    /// <param name="processes"></param>
    private void SameNameCheck(Process[] processes)
    {
        //Detected, judge whether it is to be detected, avoid the same name
        bool isfound = false;//Is it found

        foreach (Process process in processes)
        {
            string path = process.MainModule.FileName;//return value reference: C:\Windows\System32\\
otepad.exe
            if (path.Equals(@processExePath_Long, StringComparison.OrdinalIgnoreCase))//found found
            {
                isfound = true;
                break;
            }
        }

        if (isfound == false)//not found
        {
            Debug.Log("program, but with the same name");
            MyQuiitMessageBox("Warning", "Not detected" + processName + "Program starts, program exits_3");
        }
    }


    /// <summary>
    /// The UI of the exit prompt
    /// </summary>
    /// <param name="title">Title</param>
    /// <param name="content">Prompt content</param>
    private void MyQuiitMessageBox(string title, string content)
    {
        // Exit if not detected
        MessageBox(IntPtr. Zero, content, title, (int)0x000000L, () =>
        {
            ProgramExit();
        });
    }



    /// <summary>
    /// Exit under the editor, and exit after publishing
    /// </summary>
    private void ProgramExit()
    {
#if UNITY_EDITOR
        Debug.Log("The startup program was not detected, the program exited!");
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application. Quit();
#endif

    }


}