CS进程单例模式

1、SingletonExeController.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace SingletonExeTest
{
    //通过检测Mutex,确认只会启用一个进程
    //第一个进程,会启用Tcp监听,接收参数
    //后续进程,通过TcpChannel,将参数传递给第一个进程
    //使用前,必须先调用InitSingleton,使用后必须调用UninitSingleton
    class SingletonExeController : MarshalByRefObject
    {
        private static Mutex m_Mutex = null;
        private static TcpChannel m_TCPChannel = null;
        
        //初始化
        public static void InitSingleton()
        {
            string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).CodeBase;
            string uniqueIdentifier = assemblyName.Replace("\\", "_");
            m_Mutex = new Mutex(false, uniqueIdentifier);
        }

        //回收资源
        public static void UninitSingleton()
        {
            if (m_Mutex != null)
            {
                m_Mutex.Close();
            }
            m_Mutex = null;

            if (m_TCPChannel != null)
            {
                m_TCPChannel.StopListening(null);
            }
            m_TCPChannel = null;
        }

        //判断是否为第一个进程
        public static bool FirstProcToRun(int tcpPort,String serviceName)
        {
            if (m_Mutex.WaitOne(1, true))
            {
                CreateTCPChannel(tcpPort,serviceName);
                return true;
            }
            else
            {
                m_Mutex.Close();
                m_Mutex = null;
                return false;
            }
        }

        //创建TCP监听
        private static void CreateTCPChannel(int tcpPort,String serviceName)
        {
            try
            {
                m_TCPChannel = new TcpChannel(tcpPort);
                ChannelServices.RegisterChannel(m_TCPChannel, false);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(SingletonExeController), serviceName, WellKnownObjectMode.SingleCall);
            }
            catch(Exception ex)
            {
                //Fix me...
                //port in use
                MessageBox.Show(ex.Message);
            }
        }

        //后续进程,向第一个进程发送自己的参数
        public static void Send(int port,String serviceName, string[] s)
        {
            try
            {
                SingletonExeController ctrl;
                TcpChannel channel = new TcpChannel();
                ChannelServices.RegisterChannel(channel, false);
                try
                {
                    String address = "tcp://localhost:" + port + "/" + serviceName;
                    ctrl = (SingletonExeController)Activator.GetObject(typeof(SingletonExeController), address);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                    throw;
                }
                ctrl.Receive(s);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //第一个进程,接收传入参数
        public void Receive(string[] s)
        {
            //Do something here
            //...

            //Test Code
            MessageBox.Show(s[0]);
        }

        //查找第一个进程
        public static Process findMainProcess()
        {
            Process currentProcess = Process.GetCurrentProcess();
            string processName = currentProcess.ProcessName;

            Process mainProcess = null;
            Process[] allProcesses = Process.GetProcessesByName(processName);
            if (allProcesses != null)
            {
                foreach (Process p in allProcesses)
                {
                    if (p.Id != currentProcess.Id)
                    {
                        if (p.MainWindowHandle != null)
                        {
                            mainProcess = p;
                            break;
                        }
                    }
                }
            }

            return mainProcess;
        }

        //查找第一个进程的主窗口
        public static IntPtr findMainWnd()
        {
            IntPtr mainWnd = IntPtr.Zero;
            Process p = findMainProcess();
            if(p!=null && p.MainWindowHandle != null)
            {
                mainWnd=p.MainWindowHandle;
            }

            return mainWnd;
        }
    }
}

2、Program.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

namespace SingletonExeTest
{
    static class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            //Debugger.Launch();
            //Debugger.Break();

            int tcpPort = 9999;
            String serviceName = "MyTestService";

            SingletonExeController.InitSingleton();

            if (SingletonExeController.FirstProcToRun(tcpPort, serviceName))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                //Do something here
                //...

                //Test Code
                Application.Run(new MainForm());
            }
            else
            {
                IntPtr mainWnd = SingletonExeController.findMainWnd();
                Win32Utils.ShowWindow(mainWnd, Win32Utils.SW_RESTORE);
                //Real Code
                //SingletonExeController.Send(tcpPort, serviceName, args);

                //Test Code
                String[] msgs = {"hi","hello","good"};
                SingletonExeController.Send(tcpPort, serviceName, msgs);
            }

            SingletonExeController.UninitSingleton();
        }
    }
}

CS获取可执行文件所在文件夹

        //Form程序
        private static String getExeFileFolder()
        {
            String strExeFolder = System.Reflection.Assembly.GetExecutingAssembly().Location;
            int nPos = strExeFolder.LastIndexOf("\\");
            if (nPos >= 0)
            {
                strExeFolder = strExeFolder.Substring(0, nPos + 1);
            }
            else
            {
                strExeFolder = strExeFolder + "\\";
            }

            return strExeFolder;
        }

        //IIS程序
        String rootPath = Request.PhysicalApplicationPath;
        String strExeFolder = getExeFileFolder(rootPath);
        private static String getExeFileFolder(String strExeFolder)
        {
            int nPos = strExeFolder.LastIndexOf("\\");
            if (nPos >= 0)
            {
                strExeFolder = strExeFolder.Substring(0, nPos + 1);
            }
            else
            {
                strExeFolder = strExeFolder + "\\";
            }

            return strExeFolder;
        }

多线程处理

        int nMaxThreadNum = 5;
        List<List<JobParam>> jobQueue = new List<List<JobParam>>();
        //...
        for (int i = 0; i < nMaxThreadNum;i++)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncDoRetrieve), jobQueue&#91;i&#93;);
        }

        static void AsyncDoRetrieve(object state)
        {
            if (!(state == null && state is List<JobParam>)) return;
            List<JobParam> jobParams= state as List<JobParam> ;
            foreach(JobParam param in jobParams)
            {
                param.delegateDoSomeThing.BeginInvoke(param,null,null);
            }
        }

DBHelperSQLLite

1.IDBHelper.cs

    interface IDBHelper
    {
        void initDB();
        void closeDB();
        void ExecSQL(String execSql);
        DataTable ExecQuery(String querySql);
    }

2.ZDBHelperSQLLite.cs

    class ZDBHelperSQLLite : IDBHelper
    {
        String dataSource = "";
        SQLiteConnection connection = null;
        public void initDB(String dbPath)
        {
            dataSource = "Data Source =" + dbPath();
            connection = new SQLiteConnection(dbFile);
            connection.Open();
            initTables();
            CreateFileInfoTable();
        }
        
        public void closeDB()
        {
            connection.Close();
        }

        private void initTables()
        {
            String sqlCreate01 = "CREATE TABLE IF NOT EXISTS visitlog(user_id varchar(64), visit_path varchar(256), visit_time integer);";
            SQLiteCommand cmdCreateTable = new SQLiteCommand(connection);
            cmdCreateTable.CommandText = sqlCreate01;
            cmdCreateTable.ExecuteNonQuery();
        }
  
        public void ExecSQL(String execSql)
        {
            SQLiteTransaction transaction = connection.BeginTransaction();
            SQLiteCommand cmdExec = new SQLiteCommand(execSql, connection, transaction );
            cmdExec.ExecuteNonQuery();
            transaction.Commit();
        }

        public DataTable ExecQuery(String querySql)
        {
            SQLiteCommand cmdQuery = new SQLiteCommand(querySql, connection);
            SQLiteDataReader reader = cmdQuery.ExecuteReader();

            DataTable datatable = new DataTable();
            DataTable schemaTable = reader.GetSchemaTable();
            foreach (DataRow myRow in schemaTable.Rows)
            {
                DataColumn myDataColumn = new DataColumn();
                myDataColumn.DataType = myRow.GetType();
                myDataColumn.ColumnName = myRow[0].ToString();
                datatable.Columns.Add(myDataColumn);
            }
            schemaTable = null;

            while (reader.Read())
            {
                DataRow myDataRow = datatable.NewRow();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    myDataRow[i] = reader[i].ToString();
                }
                datatable.Rows.Add(myDataRow);
                myDataRow = null;
            }
            reader.Close();

            return datatable;
        }
    }

C#写WindowsService

1、新建一个Windows Service项目,重命名服务类名

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;

namespace ServiceTestCS
{
    public partial class ServiceTestCS : ServiceBase
    {
        //安装卸载时,最好用绝对路径哦
        //Installutil NASTestCS
        //Installutil -u NASTestCS

        private const int waitInterval = 200;
        private AutoResetEvent stopEvent = new AutoResetEvent(false);
        private AutoResetEvent pauseContinueEvent = new AutoResetEvent(false);
        private Thread workingThread = null;

        public NASTestCS()
        {
            InitializeComponent();
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
        }

        protected override void OnStart(string[] args)
        {
            #if DEBUG
            /*
            //等待调试器,但调试Windows服务时,提示没有加载符号
            while (!Debugger.IsAttached)
            {
                Thread.Sleep(waitInterval);
            }
            */
            Debugger.Launch();
            #endif

            workingThread = new Thread(new ThreadStart(MaiLoop));
            workingThread.Start();
        }

        protected override void OnStop()
        {
            stopEvent.Set();
        }

        protected override void OnShutdown()
        {
            stopEvent.Set();
        }

        protected override void OnPause()
        {
            pauseContinueEvent.Set();
        }

        protected override void OnContinue()
        {
            pauseContinueEvent.Set();
        }

        protected void MaiLoop()
        {
            Boolean bEnd = false;
            while (!bEnd)
            {
                //处理你的正常事务
                //但要保证下面的代码,可以定期被调用到
                //......

                //截获停止事件
                if(stopEvent.WaitOne(waitInterval))
                {
                    bEnd = true;
                    break;
                }

                //截获暂停事件
                if (pauseContinueEvent.WaitOne(waitInterval))
                {
                    //等待继续时间
                    while (!pauseContinueEvent.WaitOne(waitInterval))
                    {
                        //少占用一些资源
                        Thread.Sleep(waitInterval);

                        //暂停时也可以退出
                        if (stopEvent.WaitOne(waitInterval))
                        {
                            bEnd = true;
                            break;
                        }
                    }
                }
            }
        }
    }
}

2、服务设计界面右击,添加Service Installer
配置Service Installer,配置服务类名称,显示名称,启动类型,登录用户,服务依赖等
但如果要可以与桌面交互的话,需要添加代码实现。
双击serviceInstaller,添加下面方法:

        using System.Management;

        private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            //要用LocalSystem用户登录才有效哦
            ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", this.serviceInstaller.ServiceName));
            ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
            changeMethod["DesktopInteract"] = true;
            ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null);
        }

3、安装与反安装,用命令行实现

rem 安装服务
%PATH_TO_INSTALLUTIL%\installutil.exe %PATH_TO_SERVICE%\NASTestCS.exe
rem 卸载服务
%PATH_TO_INSTALLUTIL%\installutil.exe -u %PATH_TO_SERVICE%\NASTestCS.exe

使用命名管道实现进程间通信(下)

1、服务端C#

        private const String MY_PIPE_NAME = "__MY__PIPE__TEST__";
        private const int BUFFER_SIZE = 1024;
        NamedPipeServerStream pipe;
        StreamWriter writer;
        String msg = "Message is comming";

        private void PipeCreate()
        {
            if (pipe != null && pipe.IsConnected)
            {
                pipe.Close();
            }

            pipe = new NamedPipeServerStream(MY_PIPE_NAME, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None);
            

            if (pipe == null)
            {
                textBox1.Text = textBox1.Text + "Pipe is null";
                return;
            }

            if (pipe.IsConnected)
            {
                textBox1.Text = textBox1.Text + "Pipe is already connected";
                return;
            }

            pipe.WaitForConnection();

            textBox1.Text = textBox1.Text + "Pipe is ready to connect\r\n";
        }

        private void PipeWrite()
        {
            if (pipe!=null && pipe.IsConnected)
            {
                if(writer==null)
                {
                    //关闭BOM(Byte Order Mark 0xfeff)
                    UnicodeEncoding unicodeWithoutBom = new System.Text.UnicodeEncoding(false, false);
                    writer = new StreamWriter(pipe, unicodeWithoutBom);
                    //写完后直接flush,会阻塞
                    writer.AutoFlush = true;
                }
                writer.Write(msg);

                textBox1.Text = textBox1.Text + "Pipe message sent \r\n";
            }
            else
            {
                textBox1.Text = textBox1.Text + "Pipe is not connected \r\n";
            }
        }

        private void PipeClose()
        {
            if (pipe!=null && pipe.IsConnected)
            {
                writer.Close();
                pipe.Close();

                writer = null;
                pipe = null;
            }
        }

2、客户端C#

        private const String MY_PIPE_NAME =  "__MY__PIPE__TEST__";
        private const int BUFFER_SIZE = 1024;
        NamedPipeClientStream pipe;
        StreamReader reader;

        private void PipeConnect()
        {
            if (pipe != null && pipe.IsConnected)
            {
                pipe.Close();
            }
            pipe = new NamedPipeClientStream(".", MY_PIPE_NAME, PipeDirection.InOut);

            if (pipe != null)
            {
                if (!pipe.IsConnected)
                {
                    pipe.Connect();
                    textBox1.Text = textBox1.Text + "\r\npipe is connected";
                }
                else
                {
                    textBox1.Text = textBox1.Text + "\r\npipe is already connected";
                }
            }
            else
            {
                textBox1.Text = textBox1.Text + "\r\npipe is null";
            }

            
        }

        private void PipeRead()
        {
            if (pipe.IsConnected)
            {
                if (reader == null)
                {
                    reader = new StreamReader(pipe, Encoding.Unicode);
                }

                char[] buffer = new char[BUFFER_SIZE];
                int byteRead = reader.Read(buffer, 0, BUFFER_SIZE);
                String msgTxt = new String(buffer, 0, byteRead);
                textBox1.Text = textBox1.Text + "\r\nPipe msg received: " + msgTxt;
            }
            else
            {
                textBox1.Text = textBox1.Text + "\r\nPipe is not connected";
            }
        }

        private void PipeClose()
        {
            if (reader != null)
            {
                reader.Close();
                reader = null;
            }
            if (pipe != null && pipe.IsConnected)
            {
                pipe.Close();
            }

            textBox1.Text = textBox1.Text + "\r\npipe is closed";
        }

匿名管道重定向命令行输出

首先是MFC,注意事项:
1、管道读写是FIFO
2、读写指针,要记得关闭
3、编译时用了UNICODE,但CMD读取回来时ANSI,所以要转换一下字符集

	SECURITY_ATTRIBUTES sa;
	ZeroMemory(&sa, sizeof(sa));
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;

	HANDLE hRead, hWrite;
	if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
		MessageBox(L"Error On CreatePipe()");
		return;
	}

	STARTUPINFO si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(STARTUPINFO);
	GetStartupInfo(&si);
	si.hStdError = hWrite;
	si.hStdOutput = hWrite;
	si.wShowWindow = SW_HIDE;
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));
	if (!::CreateProcess(L"C:\\Windows\\System32\\cmd.exe", L"/c dir /b D:\\Downloads"
		, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) {
		showMeErrorInfo();	
		return;
	}
	CloseHandle(hWrite);

	char buffer[4096] = { 0 };
	DWORD bytesRead;
	while (true) {
		if (ReadFile(hRead, buffer, 4095, &bytesRead, NULL) == NULL)
		{
			break;
		}
		
		UINT CodePage = 0;
		DWORD dwNum;
		dwNum = MultiByteToWideChar(CodePage, 0, buffer, -1, NULL, 0);
		if (dwNum)
		{
			wchar_t *pwText;
			pwText = new TCHAR[dwNum];
			if (pwText)
			{
				MultiByteToWideChar(CodePage, 0, buffer, -1, pwText, dwNum);
			}
			//m_Edit.SetWindowText(pwText);
			delete[]pwText;
			pwText = NULL;
		}
		UpdateData(false);
		Sleep(200);
	}
	CloseHandle(hRead);

C#的话,就简单多了:

            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "C:\\Windows\\System32\\cmd.exe";
            startInfo.Arguments = "/c dir /b D:\\Downloads";
            startInfo.RedirectStandardOutput = true;
            //startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = false;
           
            Process p=Process.Start(startInfo);

            String cmdOut = "";
            while(!p.HasExited)
            { 
                cmdOut = p.StandardOutput.ReadLine();
                textBox1.Text += cmdOut + "\r\n";
                p.WaitForExit(10);
            }
            cmdOut = p.StandardOutput.ReadToEnd() + "\r\n";
            textBox1.Text += cmdOut ;

使用WM_COPYDATA实现跨进程通讯(下)

请注意:
A、SendMessage在接收方处理完毕前不会返回,会产生严重阻塞
B、由于使用了非托管内存,要注意进行清理

1、发送方WinForm

        public const int WM_COPYDATA = 0x004A;
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            public IntPtr lpData;
        }

        public void sendData(String msg, Boolean isUnicode)
        {
            COPYDATASTRUCT cds = new COPYDATASTRUCT();
            cds.cbData = (msg.Length + 1) * (isUnicode ? 2:1);
            cds.lpData = (isUnicode ? Marshal.StringToCoTaskMemUni(msg) : Marshal.StringToCoTaskMemAnsi(msg));

            IntPtr cdsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(cds));
            Marshal.StructureToPtr(cds, cdsPtr, false);

            IntPtr clientWnd = Win32Helper.GetCurrentWindowHandle();
            SendMessage(clientWnd, WM_COPYDATA, IntPtr.Zero, cdsPtr);

            Marshal.FreeHGlobal(cdsPtr);
            Marshal.FreeCoTaskMem(cds.lpData);
        }

2、接收方WinForm

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        private struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            public string lpData;
        }

        public const int WM_COPYDATA = 0x004A;
        protected override void WndProc(ref System.Windows.Forms.Message msg)
        {
            string msgTxt = "";
            COPYDATASTRUCT cds = new COPYDATASTRUCT();
            switch (msg.Msg)
            {
                case WM_COPYDATA:
                    if(msg.LParam!=IntPtr.Zero)
                    {
                        cds = (COPYDATASTRUCT)msg.GetLParam(cds.GetType());
                        String msgstr = cds.lpData;
                        //MessageBox.Show(msgstr);
                    }
                    break;
                default:
                    base.WndProc(ref msg);
                    break;
            }
        }

C#获取dll自身路径

            //获取dll的绝对路径,请根据不同情况自己选用
            MessageBox.Show(System.Reflection.Assembly.GetExecutingAssembly().Location);
            MessageBox.Show(System.Reflection.Assembly.GetEntryAssembly().Location);   
            MessageBox.Show(System.Windows.Forms.Application.ExecutablePath);
            MessageBox.Show(System.Windows.Forms.Application.StartupPath);
            MessageBox.Show(System.Environment.CurrentDirectory);
            MessageBox.Show(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);

C#枚举窗口句柄

在CS程序中启动其他应用后,要获取进程的主窗体其实很简单:

        Process p = Process.Start(exePath);
        //p.WaitForInputIdle();
        p.Refresh(); 
        IntPtr mainWnd = p.MainWindowHandle;

但是,总有很多特殊的情况,上面的方法根本无法用,所以,要用Windows API来搞定了

1、如果窗口信息很固定而且没有重名的话,可以用Findwindow搞定

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        IntPtr clientWnd = FindWindow(null,"FormClient");

2、根据标题枚举窗口句柄

        //枚举窗体
        [DllImport("User32.dll", EntryPoint = "EnumWindows", SetLastError = true)]
        public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, uint lParam);
        //获取窗体标题
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpText, int nCount);
        //设置错误状态
        [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
        public static extern void SetLastError(uint dwErrCode);

        //线程主窗口句柄
        private static IntPtr processMainWnd = IntPtr.Zero;
        //要查找的窗口名称
        private static String winTitle = "__Web__Form__Main__";

        //声明委托函数
        public delegate bool WNDENUMPROC(IntPtr hwnd, uint lParam);

        //枚举进程句柄,非线程安全
        [SecuritySafeCritical]
        public static IntPtr GetCurrentWindowHandle()
        {
            IntPtr ptrWnd = IntPtr.Zero;

            bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), (uint)0);
            if (!bResult && Marshal.GetLastWin32Error() == 0)
            {
                ptrWnd = processMainWnd;
            }

            return ptrWnd;
        }

        //枚举函数,获取主窗口句柄然后退出
        [SecuritySafeCritical]
        private static bool EnumWindowsProc(IntPtr hwnd, uint lParam)
        {
            //根据标题获取窗体
            var sb = new StringBuilder(50);
            GetWindowText(hwnd, sb, sb.Capacity);

            if (winTitle.Equals(sb.ToString()))
            {
                processMainWnd = hwnd;
                SetLastError(0);
                return false;
            }

            return true;
        }

3、跟进进程id枚举获取主窗体句柄

        //枚举窗体
        [DllImport("User32.dll", EntryPoint = "EnumWindows", SetLastError = true)]
        //获取父窗体
        [DllImport("user32.dll", EntryPoint = "GetParent", SetLastError = true)]
        //根据窗口获取线程句柄
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out uint pid);
        //设置错误状态
        [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
        public static extern void SetLastError(uint dwErrCode);

        //线程主窗口句柄
        private static IntPtr processMainWnd = IntPtr.Zero;

        //枚举进程句柄
        [SecuritySafeCritical]
        public static IntPtr GetCurrentWindowHandle(int processId)
        {
            IntPtr ptrWnd = IntPtr.Zero;

            bool bResult = EnumWindows(new WNDENUMPROC(EnumWindowsProc), (uint)processId);
            if (!bResult && Marshal.GetLastWin32Error() == 0)
            {
                ptrWnd = processMainWnd;
            }

            return ptrWnd;
        }

        //枚举函数,获取主窗口句柄然后退出
        [SecuritySafeCritical]
        private static bool EnumWindowsProc(IntPtr hwnd, uint lParam)
        {
            uint uiPid = 0;
            //根据启动方式不同,这里要有相应修改
            if (GetParent(hwnd) == IntPtr.Zero)
            {
                GetWindowThreadProcessId(hwnd, out uiPid);
                if (uiPid == lParam)
                {
                    processMainWnd = hwnd;
                    SetLastError(0);
                    return false;
                }
            }
        }

4、跟进窗口WindowsClassName举获取主窗体句柄

        //查找桌面
        [DllImport("User32.dll", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
        public static extern IntPtr GetDesktopWindow();
        //获取窗体句柄
        [DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        public static extern IntPtr GetWindow(IntPtr hwnd, int wFlag);
        //获取窗体类
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        public const int GW_CHILD = 5;
        public const int GW_HWNDNEXT = 2;

        //枚举桌面窗口,根据WindowsClassName获取句柄
        [SecuritySafeCritical]
        public static IntPtr GetWinHandleByClasName(String windowClassNmae)
        {   
            //取得桌面窗口,再获取第一个子窗口
            IntPtr hwnd = GetDesktopWindow();
            hwnd = GetWindow((IntPtr)hwnd, System.Convert.ToInt32(GW_CHILD));
            
            //通过循环来枚举所有的子窗口
            while ((long)hwnd != 0)
            {
                System.Text.StringBuilder ClassName = new System.Text.StringBuilder(256);
                GetClassName((IntPtr)hwnd, ClassName, ClassName.Capacity);
                String tmpClassName= ClassName.ToString().Trim();
                if (tmpClassName.Length > 0)
                {
                    if (tmpClassName.Equals(windowClassNmae))
                    {
                        break;
                    }
                }

                hwnd = GetWindow((IntPtr)hwnd, System.Convert.ToInt32(GW_HWNDNEXT));
            }

            return hwnd;
        }