public bool TryClose(int timeout_ms = 0)
        {
            try
            {
                logger.Debug("Attempting to close process...");
                process.Refresh();

                var success = process.CloseMainWindow();

                if (success)
                {
                    logger.Debug("Successfully sent close message to main window.");
                }
                else
                {
                    logger.Warn("Failed to send close message to main window!");
                }

                return(success && WaitForTermination(timeout_ms));
            }
            catch (Exception e)
            {
                logger.Error("Failed to close main window!", e);
            }

            return(false);
        }
Example #2
0
 private void ForceRefresh()
 {
     lock (m_sync)
     {
         m_lastRefresh = DateTime.UtcNow;
         m_process.Refresh();
     }
 }
        private static void VerifyProcess(Process p, DiagnosticsProcess process)
        {
            Assert.AreEqual(process.Id, p.Pid);

            RetryOnAssert(() =>
            {
                process.Refresh();
                p.Refresh();
#if NET3PLUS
                if (process.ProcessName != p.Name)
                {
                    // .NET Core 3.x breaking change
                    Assert.IsTrue(p.CommandLine.Contains(process.ProcessName), $"Process name mismatch: {p.Name} ({p.CommandLine}) - {process.ProcessName}");
                }
#else
                Assert.AreEqual(process.ProcessName, p.Name);
#endif
            });

            Assert.IsNotNull(p.CommandLine);
            Assert.AreEqual(process.StartTime.ToUniversalTime(), p.StartTimeUtc);

            RetryOnAssert(() =>
            {
                process.Refresh();
                p.Refresh();
                Assert.AreEqual(process.VirtualMemorySize64, p.VirtualMemorySize);
            });

            RetryOnAssert(() =>
            {
                process.Refresh();
                p.Refresh();
                Assert.AreEqual(process.WorkingSet64, p.ResidentSetSize);
            });

            RetryOnAssert(() =>
            {
                process.Refresh();
                p.Refresh();
                Assert.AreEqual(process.UserProcessorTime.TotalSeconds, p.UserProcessorTime, CpuError);
            });

            RetryOnAssert(() =>
            {
                process.Refresh();
                p.Refresh();
                Assert.AreEqual(process.PrivilegedProcessorTime.TotalSeconds, p.KernelProcessorTime, CpuError);
            });
        }
Example #4
0
        // 使用メモリ
        static public void OutPutMemory()
        {
            System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
            p.Refresh();

            Console.WriteLine("メモリ使用量(MB): {0}", p.WorkingSet64 / 1024 / 1024);
        }
Example #5
0
        public static void fixWorkingDirectory()
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            string path = Application.ExecutablePath;
            int    i    = path.LastIndexOf('\\');

            proc.StartInfo.FileName         = path.Substring(i + 1);
            proc.StartInfo.WorkingDirectory = path.Substring(0, i);
            proc.StartInfo.Arguments        = "wdfix";
            proc.Start();

            while (true)
            {
                try
                {
                    proc.Refresh();
                    if (proc.Modules.Count > 1)
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(10);
                }
                catch { }
            }
            Application.DoEvents();
            System.Threading.Thread.Sleep(1000);
            kill();
        }
Example #6
0
        public void Update(GameTime gameTime)
        {
            if (process == null)
            {
                return;
            }


            this.elapsedTime += gameTime.ElapsedGameTime.Ticks;
            if (this.elapsedTime <= 10000000L)
            {
                return;
            }
            process.Refresh();

            this.elapsedTime   -= 10000000L;
            this.frameRate      = this.frameCounter;
            this.frameCounter   = 0;
            this.currentMemory  = process.WorkingSet64;
            this.totalMemory    = process.PeakWorkingSet64;
            this.currentMemory /= 1048576L;
            this.totalMemory   /= 1048576L;

            this.sb.Clear();
            this.sb.Append("fps: ")
            .Append(frameRate)
            .Append(" CMem: ")
            .Append(currentMemory)
            .Append(" TMem: ")
            .Append(totalMemory);
        }
Example #7
0
        public void Kill()
        {
            process.Refresh();

            if (!process.HasExited)
            {
                process.Kill();
            }
        }
Example #8
0
 // Process Kill
 public void killProcess(uint processID)
 {
     // ProcessID가 0이 아닐 경우 (종료되지 않음)
     if (processID != 0)
     {
         System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessById((int)processID);
         process.CloseMainWindow();
         process.Refresh();
         process.Kill();
     }
 }
Example #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();

            op.Filter          = "Application|*.exe";
            op.CheckFileExists = true;
            op.CheckPathExists = true;

            if (op.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            //Se já existe um app carregado dentro do Panel, fecha ele
            if (Child != IntPtr.Zero)
            {
                Win32.CloseWindow(Child);
                Child = IntPtr.Zero;
            }

            //Inicia o app, e aguarda até que a janela principal seja carregada
            System.Diagnostics.Process p = System.Diagnostics.Process.Start(op.FileName);
            while (p.MainWindowHandle == IntPtr.Zero)
            {
                p.Refresh();
                System.Threading.Thread.Sleep(200);
            }


            Child = p.MainWindowHandle;
#if NO_STYLE
            //--------------------------------
            //Retira a barra de título e as bordas da Janela do app externo
            int winLong = Win32.GetWindowLong(Child, Win32.GWL_STYLE);

            winLong &= ~((int)Win32.WS.WS_CAPTION | (int)Win32.WS.WS_THICKFRAME |
                         (int)Win32.WS.WS_MINIMIZE | (int)Win32.WS.WS_MAXIMIZE);

            winLong &= ~((int)Win32.WS.WS_EX_DLGMODALFRAME |
                         (int)Win32.WS.WS_EX_CLIENTEDGE | (int)Win32.WS.WS_EX_STATICEDGE | (int)Win32.WS.WS_POPUP);

            Win32.SetWindowLong(Child, Win32.GWL_STYLE, winLong);

            //------------------------------
            //Define a janela do app externo como filha do Panel
#endif
            Win32.SetParent(Child, panel1.Handle);
            Win32.ShowWindow(Child, Win32.nCmdShow.SW_SHOWMAXIMIZED);
            //Define a posição e o tamanho da Janela dentro do Panel
#if NO_STYLE
            Win32.SetWindowPos(Child, IntPtr.Zero, 0, 0, panel1.Size.Width, panel1.Size.Height, (uint)((uint)Win32.SWPF.FRAMECHANGED
                                                                                                       | (uint)Win32.SWPF.NOZORDER | (uint)Win32.SWPF.NOOWNERZORDER));
#endif
        }
 protected void Dispose(bool disposing)
 {
     if (!this.disposedValue)
     {
         try
         {
             if (_ExcelApplication != null)
             {
                 foreach (Microsoft.Office.Interop.Excel.Workbook WorkBookName in _ExcelApplication.Workbooks)
                 {
                     WorkBookName.Close(false);
                 }
                 IntPtr iHandle = IntPtr.Zero;
                 iHandle = new IntPtr(_ExcelApplication.Parent.Hwnd);
                 _ExcelApplication.DisplayAlerts = false;
                 _ExcelApplication.Quit();
                 System.Runtime.InteropServices.Marshal.ReleaseComObject(_ExcelApplication);
                 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_ExcelApplication);
                 SetLastError(0);
                 if (IntPtr.Equals(iHandle, IntPtr.Zero))
                     iHandle = FindWindow(null, _caption);
                 if (!IntPtr.Equals(iHandle, IntPtr.Zero))
                 {
                     int iRes;
                     uint iProcId;
                     iRes = (int)GetWindowThreadProcessId(iHandle, out iProcId);
                     if (iProcId == 0)
                     {
                         if (EndTask(iHandle) == 0)
                             throw new ApplicationException("Excel Instance Could Not Be Closed");
                     }
                     else
                     {
                         System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById((int)iProcId);
                         proc.CloseMainWindow();
                         proc.Refresh();
                         if (!proc.HasExited)
                             proc.Kill();
                     }
                 }
             }
         }
         finally
         {
             _ExcelApplication = null;
             GC.WaitForPendingFinalizers();
             GC.Collect();
             GC.WaitForPendingFinalizers();
             GC.Collect();
         }
     }
     this.disposedValue = true;
 }
Example #11
0
        public void StartXBMC()
        {
            try
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo = new System.Diagnostics.ProcessStartInfo(c.path);

                Log.LogLine("Starting XBMC...");
                p.Start();

                while (p.MainWindowHandle == IntPtr.Zero)
                {
                    Thread.Sleep(200);
                    p.Refresh();
                }

                Log.LogLine("Main Window Handle {0}", p.MainWindowHandle.ToInt32());
                switch (c.bring_window_to_front_mode)
                {
                case 1:
                    if (c.TopMost)
                    {
                        Log.LogLine("SetWindowPos TopMost {0}", p.MainWindowHandle.ToInt32());
                        SetWindowPos(p.MainWindowHandle, HWND_TOPMOST, 50, 50, 500, 500, SetWindowPosFlags.IgnoreMove | SetWindowPosFlags.IgnoreResize);
                    }
                    else
                    {
                        Log.LogLine("SetWindowPos {0}", p.MainWindowHandle.ToInt32());
                        SetWindowPos(p.MainWindowHandle, HWND_TOP, 50, 50, 500, 500, SetWindowPosFlags.IgnoreMove | SetWindowPosFlags.IgnoreResize);
                    }
                    break;

                case 2:
                    Log.LogLine("BringWindowToTop {0}", p.MainWindowHandle.ToInt32());
                    BringWindowToTop(p.MainWindowHandle);
                    break;

                case 3:
                    Log.LogLine("SetForegroundWindow {0}", p.MainWindowHandle.ToInt32());
                    SetForegroundWindow(p.MainWindowHandle);
                    break;

                case 4:
                    Log.LogLine("SetFocus {0}", p.MainWindowHandle.ToInt32());
                    SetFocus(p.MainWindowHandle);
                    break;
                }
            }
            catch (InvalidOperationException)
            {
                Log.LogLine("XBMC is already running!");
            }
        }
Example #12
0
        public void SaveAsExcel(List <List <string> > result) // 게임마다 엑셀 저장방식은 다름
        {
            string name = Getgamename();

            if ((name = Filelocation(name)) != "")
            {
                Excel.Application excelApp  = new Excel.Application();
                Excel.Workbook    workBook  = excelApp.Workbooks.Add();
                Excel.Worksheet   workSheet = workBook.Worksheets.get_Item(1) as Excel.Worksheet;
                workSheet.Cells[1, 1] = "고유 번호";
                workSheet.Cells[1, 2] = "학교명";
                workSheet.Cells[1, 3] = "학년";
                workSheet.Cells[1, 4] = "번호";
                workSheet.Cells[1, 5] = "성별";
                workSheet.Cells[1, 6] = "이름";
                for (int i = 0; i < result.Count; i++)
                {
                    for (int j = 2; j < result[i].Count; j++)
                    {
                        workSheet.Columns[5 + j].NumberFormat = "@";
                        workSheet.Cells[i + 1, 5 + j]         = result[i][j];
                    }
                }
                for (int i = 1; i < result.Count; i++)
                {
                    int j = 1;
                    if (!result[i][1].StartsWith("unknown"))
                    {
                        foreach (string s in Getstudent(Convert.ToInt32(result[i][0])))
                        {
                            workSheet.Cells[i + 1, j++] = s;
                        }
                    }
                    else
                    {
                        workSheet.Cells[i + 1, 6] = result[i][1];
                    }
                }
                workSheet.Columns.AutoFit();
                workBook.SaveAs(name);
                workBook.Close(true);
                GetWindowThreadProcessId(new IntPtr(excelApp.Hwnd), out uint processId);
                excelApp.Quit();
                if (processId != 0)
                {
                    System.Diagnostics.Process excelProcess = System.Diagnostics.Process.GetProcessById((int)processId);
                    excelProcess.CloseMainWindow();
                    excelProcess.Refresh();
                    excelProcess.Kill();
                }
            }
        }
Example #13
0
        public static String processInfo()
        {
            String res = "私のプロセス情報だよ!\n";

            System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
            p.Refresh();
            res += "プロセスID:" + p.Id + "\n";
            res += "プロセス名:" + p.ProcessName + "\n";
            res += "基本優先度:" + p.BasePriority + "\n";
            res += "物理メモリ:" + p.WorkingSet64 + "\n";
            res += "仮想メモリ:" + p.VirtualMemorySize64 + "\n";
            return(res);
        }
Example #14
0
 public void Print(string sreport)
 {
     //PrintDialog printDialog1 = new PrintDialog();
     //printDialog1.PrinterSettings.PrinterName = "EasyCoder 91 DT (203 dpi)";
     System.Diagnostics.Process process = new System.Diagnostics.Process();
     process.Refresh();
     //process.StartInfo.Arguments = "EasyCoder 91 DT (203 dpi)";
     process.StartInfo.CreateNoWindow  = true;
     process.StartInfo.Verb            = "print";
     process.StartInfo.FileName        = @sreport;
     process.StartInfo.UseShellExecute = true;
     process.StartInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
     process.Start();
 }
Example #15
0
        public void ExitExcel(Microsoft.Office.Interop.Excel.Application application)
        {
            uint processId = 0;

            GetWindowThreadProcessId(new IntPtr(application.Hwnd), out processId);
            application.Quit();
            if (processId != 0)
            {
                System.Diagnostics.Process excelProcess = System.Diagnostics.Process.GetProcessById((int)processId);
                excelProcess.CloseMainWindow();
                excelProcess.Refresh();
                excelProcess.Kill();
            }
        }
        public bool WaitForExit(int milliseconds)
        {
            if (_process.WaitForExit(milliseconds))
            {
                return(true);
            }

            _process.Refresh();
            if (!_process.HasExited)
            {
                _process.Kill();
            }

            return(false);
        }
Example #17
0
 public void Close() //열려있는 모든 excel 객체 해제
 {
     try
     {
         uint processId = 0;
         foreach (KeyValuePair <string, Excel.Workbook> item in eWB)
         {
             item.Value.Close(0);
         }
         foreach (KeyValuePair <string, Excel.Application> item in eXL)
         {
             GetWindowThreadProcessId(new IntPtr(item.Value.Hwnd), out processId);
             item.Value.Quit();
             if (processId != 0)
             {
                 System.Diagnostics.Process excelProcess = System.Diagnostics.Process.GetProcessById((int)processId);
                 excelProcess.CloseMainWindow();
                 excelProcess.Refresh();
                 excelProcess.Kill();
             }
         }
         //foreach (KeyValuePair<string, Excel.Sheets> item in eWS)
         //ReleaseExcelObject(item.Value);
         foreach (KeyValuePair <string, Excel.Workbook> item in eWB)
         {
             ReleaseExcelObject(item.Value);
         }
         foreach (KeyValuePair <string, Excel.Application> item in eXL)
         {
             ReleaseExcelObject(item.Value);
         }
         //eWS.Clear();
         eWB.Clear();
         eXL.Clear();
         colvalbyCenterName.Clear();
         colvalbyThezoneName.Clear();
         SumFlag.Clear();
         centerWS  = null;
         thezoneWS = null;
         minbound  = 4; maxbound = 0; columncnt = 0; totalrow = 0;
     }
     catch (Exception) { }
 }
Example #18
0
        private static void VDBMenuOption()
        {
            string vdbExe         = System.IO.Path.GetFullPath("Packages/com.havok.physics/Tools/VisualDebugger/HavokVisualDebugger.exe");
            string vdbProcessName = System.IO.Path.GetFileNameWithoutExtension(vdbExe);

            // Find all the instances of the VDB or make a new one
            List <System.Diagnostics.Process> processes = new List <System.Diagnostics.Process>();

            processes.AddRange(System.Diagnostics.Process.GetProcessesByName(vdbProcessName));
            if (processes.Count == 0)
            {
                var process = new System.Diagnostics.Process();
                process.StartInfo.FileName = vdbExe;
                // TODO: launch instance with specific connection settings
                process.StartInfo.Arguments = "";
                process.Start();
                process.WaitForInputIdle();
                process.Refresh();
                processes.Add(process);
            }

            // Bring the main window of the VDB processes to the foreground.
            IntPtr hWnd = IntPtr.Zero;

            do
            {
                hWnd = FindWindowEx(IntPtr.Zero, hWnd, null, null);
                GetWindowThreadProcessId(hWnd, out int iProcess);
                if (processes.Exists(process => process.Id == iProcess))
                {
                    int textLength = GetWindowTextLength(hWnd);
                    System.Text.StringBuilder winText = new System.Text.StringBuilder(textLength + 1);
                    GetWindowText(hWnd, winText, winText.Capacity);
                    // VDB main window title is "Havok Visual Debugger (<ip address>:<port>)"
                    // TODO: search for specific instance that matches connection settings
                    const string wName = "Havok Visual Debugger";
                    if (winText.ToString().StartsWith(wName))
                    {
                        ForceWindowIntoForeground(hWnd);
                    }
                }
            }while (hWnd != IntPtr.Zero);
        }
Example #19
0
        public static void runNotePad(String message)
        {
            #region [ 启动记事本 ]

            System.Diagnostics.Process Proc;

            try
            {
                // 启动记事本
                Proc = new System.Diagnostics.Process();
                Proc.StartInfo.FileName = "notepad.exe";
                Proc.StartInfo.UseShellExecute = false;
                Proc.StartInfo.RedirectStandardInput = true;
                Proc.StartInfo.RedirectStandardOutput = true;

                Proc.Start();
            }
            catch
            {
                Proc = null;
            }

            #endregion

            #region [ 传递数据给记事本 ]

            if (Proc != null)
            {
                // 调用 API, 传递数据
                while (Proc.MainWindowHandle == IntPtr.Zero)
                {
                    Proc.Refresh();
                }

                IntPtr vHandle = FindWindowEx(Proc.MainWindowHandle, IntPtr.Zero, "Edit", null);

                // 传递数据给记事本
                SendMessage(vHandle, WM_SETTEXT, 0, message);
            }

            #endregion
        }
Example #20
0
        public static void NewNotePad(string message)
        {
            #region [ 启动记事本 ]

            System.Diagnostics.Process Proc;

            try
            {
                // 启动记事本
                Proc = new System.Diagnostics.Process();
                Proc.StartInfo.FileName               = "notepad.exe";
                Proc.StartInfo.UseShellExecute        = false;
                Proc.StartInfo.RedirectStandardInput  = true;
                Proc.StartInfo.RedirectStandardOutput = true;

                Proc.Start();
            }
            catch
            {
                Proc = null;
            }

            #endregion

            #region [ 传递数据给记事本 ]

            if (Proc != null)
            {
                // 调用 API, 传递数据
                while (Proc.MainWindowHandle == IntPtr.Zero)
                {
                    Proc.Refresh();
                }

                IntPtr vHandle = FindWindowEx(Proc.MainWindowHandle, IntPtr.Zero, "Edit", null);

                // 传递数据给记事本
                SendMessage(vHandle, WM_SETTEXT, 0, message);
            }

            #endregion
        }
Example #21
0
        private void tsmiCount_Click(object sender, EventArgs e)
        {
            #region [ 启动记事本 ]

            System.Diagnostics.Process Proc;

            try
            {
                // 启动记事本
                Proc = new System.Diagnostics.Process();
                Proc.StartInfo.FileName               = "notepad.exe";
                Proc.StartInfo.UseShellExecute        = false;
                Proc.StartInfo.RedirectStandardInput  = true;
                Proc.StartInfo.RedirectStandardOutput = true;

                Proc.Start();
            }
            catch
            {
                Proc = null;
            }

            #endregion

            #region [ 传递数据给记事本 ]

            if (Proc != null)
            {
                // 调用 API, 传递数据
                while (Proc.MainWindowHandle == IntPtr.Zero)
                {
                    Proc.Refresh();
                }

                IntPtr vHandle = FindWindowEx(Proc.MainWindowHandle, IntPtr.Zero, "Edit", null);

                // 传递数据给记事本
                SendMessage(vHandle, WM_SETTEXT, 0, "");
            }

            #endregion
        }
Example #22
0
        private async System.Threading.Tasks.Task WaitForIdleAsync()
        {
            bool      isIdle    = false;
            const int threshold = 10;

            while (!isIdle)
            {
                System.TimeSpan startCpuTime = _process.TotalProcessorTime;

                await System.Threading.Tasks.Task.Delay(threshold);

                _process.Refresh();

                System.TimeSpan endCpuTime = _process.TotalProcessorTime;

                isIdle = (endCpuTime - startCpuTime < System.TimeSpan.FromMilliseconds(threshold));
            } // Whend

            OnIdle?.Invoke();
        } // End Task WaitForIdleAsync
Example #23
0
        public static void StartTestityProcess(string dllPath, string testityAppPath)
        {
            System.Diagnostics.Process testityProcess = null;

            //see https://msdn.microsoft.com/en-us/library/e8zac0ca(v=vs.110).aspx for error reasons
            try
            {
                testityProcess = System.Diagnostics.Process.Start(testityAppPath, dllPath);
            }
            catch (Win32Exception e)
            {
                Debug.LogErrorFormat("Unknown error attempting to launch Testity. Could not generate DLL for {0}. Error: {1}", dllPath, e.Message);
                throw;
            }
            catch (FileNotFoundException e)
            {
                Debug.LogErrorFormat("Unable to launch the Testity build application. Error: {0}", e.Message);
                throw;
            }

            //now we must block the thread and wait for the processing to finish.
            //this is probably not a good way to do this Unity doesn't offer a very good extendable pipeline
            while (!testityProcess.HasExited)
            {
                //refresh for up-to-date polling. May not be required
                testityProcess.Refresh();

                testityProcess.WaitForExit(100);

                //this is already a total mess so let's throw in a thread sleep for good measure
                Thread.Sleep(500);
            }

            //at this point the process has completed
            //if it's code 0 then it was a success and we need to reload the asset database
            AssetDatabase.ImportAsset(dllPath.TrimEnd(".dll".ToCharArray()) + ".MonoBehaviours.dll");             //we make the bold assumption that this won't change
        }
Example #24
0
        public static void fixWorkingDirectory()
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            string path = Application.ExecutablePath;
            int i = path.LastIndexOf('\\');
            proc.StartInfo.FileName = path.Substring(i + 1);
            proc.StartInfo.WorkingDirectory = path.Substring(0, i);
            proc.StartInfo.Arguments = "wdfix";
            proc.Start();

            while (true)
            {
                try
                {
                    proc.Refresh();
                    if (proc.Modules.Count > 1) break;
                    System.Threading.Thread.Sleep(10);
                }
                catch { }
            }
            Application.DoEvents();
            System.Threading.Thread.Sleep(1000);
            kill();
        }
Example #25
0
        private void abrirexe()
        {
            #region Abrir_exe
            p = System.Diagnostics.Process.Start(path_project + "//" + Nome_do_projeto + "//" + "Debug//CompilaLadder4.exe");
            while (p.MainWindowHandle == IntPtr.Zero)
            {
                p.Refresh();
                System.Threading.Thread.Sleep(200);
            }
            Child = p.MainWindowHandle;
            Win32.SetParent(Child, tabPage2.Handle);
            Win32.ShowWindow(Child, Win32.nCmdShow.SW_SHOWMAXIMIZED);
            #endregion

            #region Personalizar_exe
            //Retira a barra de título e as bordas da Janela do app externo
            int winLong = Win32.GetWindowLong(Child, Win32.GWL_STYLE);
            winLong &= ~((int)Win32.WS.WS_EX_DLGMODALFRAME | (int)Win32.WS.WS_EX_CLIENTEDGE | (int)Win32.WS.WS_EX_STATICEDGE | (int)Win32.WS.WS_POPUP);
            winLong &= ~((int)Win32.WS.WS_CAPTION | (int)Win32.WS.WS_THICKFRAME | (int)Win32.WS.WS_MINIMIZE | (int)Win32.WS.WS_MAXIMIZE);
            Win32.SetWindowLong(Child, Win32.GWL_STYLE, winLong);
            //redefine o tamanho
            Win32.SetWindowPos(Child, IntPtr.Zero, 0, 0, 700, tabPage2.Height, (uint)((uint)Win32.SWPF.FRAMECHANGED | (uint)Win32.SWPF.NOZORDER | (uint)Win32.SWPF.NOOWNERZORDER));
            #endregion
        }
Example #26
0
        public void PCBMfg_WorkflowTests()
        {
            var    pathTestbench = "/@TestBenches|kind=Testing|relpos=0/PCB_Manufacturing|kind=TestBench|relpos=0";
            String testName      = System.Reflection.MethodBase.GetCurrentMethod().Name;
            String pathOutput    = Path.Combine(project.GetRootDirectoryPath(),
                                                "output",
                                                testName);
            string configAbsPath = "/@ComponentAssemblies|kind=ComponentAssemblies|relpos=0/@AstableMultivibrator|kind=ComponentAssembly|relpos=0";


            // CyPhy2PCBMfg.CyPhy2PCBMfgInterpreter interpreter = null;

            MgaObject objTestbench = null;
            MgaFCO    configObj    = null;

            project.PerformInTransaction(delegate
            {
                objTestbench = project.get_ObjectByPath(pathTestbench);
                Assert.NotNull(objTestbench);

                configObj = project.get_ObjectByPath(configAbsPath) as MgaFCO;
                Assert.NotNull(configObj);
            });

            bool   postToJobManager = false;
            bool   keepTempModels   = false;
            bool   result           = false;
            string outputDirectory  = "";

            // Use the master Interpreter to create a JSON file in the results folder based on the Testbench's Workflow
            using (var masterInterpreter = new CyPhyMasterInterpreter.CyPhyMasterInterpreterAPI(project))
            {
                masterInterpreter.Logger.GMEConsoleLoggingLevel = CyPhyGUIs.SmartLogger.MessageType_enum.Debug;

                var miResults = masterInterpreter.RunInTransactionOnOneConfig(objTestbench as MgaModel, configObj, postToJobManager, keepTempModels);
                outputDirectory = miResults[0].OutputDirectory;

                result = miResults.Any(x => x.Success == false) ? false : true;
            }
            Assert.True(result);
            string manifestFileName   = "testbench_manifest.json";
            var    pathToManifestFile = Path.Combine(outputDirectory, manifestFileName);

            Assert.True(File.Exists(pathToManifestFile));
            var fileContents = File.ReadAllText(pathToManifestFile);

            Assert.False(String.IsNullOrWhiteSpace(fileContents));

            // Use a process to start a Python script to execute the JSON file, similar to the Job Manager, but with synchronous execution.
            // See LocalPool.cs around lines 165-186, from the CyPhyMl solution, TestBenchExecutionFramework folder, JobManager project.
            using (var proc0 = new System.Diagnostics.Process())
            {
                proc0.StartInfo.FileName               = META.VersionInfo.PythonVEnvExe;
                proc0.StartInfo.Arguments              = "-m testbenchexecutor testbench_manifest.json";
                proc0.StartInfo.UseShellExecute        = false;
                proc0.StartInfo.CreateNoWindow         = true;
                proc0.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Minimized;
                proc0.StartInfo.WorkingDirectory       = Path.Combine(outputDirectory);
                proc0.StartInfo.RedirectStandardError  = true;
                proc0.StartInfo.RedirectStandardOutput = true;

                proc0.Start();

                StringBuilder output = new StringBuilder();
                proc0.ErrorDataReceived += (o, dataArgs) =>
                {
                    if (dataArgs.Data != null)
                    {
                        try
                        {
                            output.Append(dataArgs.Data);
                        }
                        catch (ObjectDisposedException) { }
                    }
                };
                proc0.OutputDataReceived += (o, dataArgs) =>
                {
                    if (dataArgs.Data != null)
                    {
                        try
                        {
                            output.Append(dataArgs.Data);
                        }
                        catch (ObjectDisposedException) { }
                    }
                };
                proc0.BeginOutputReadLine();
                proc0.BeginErrorReadLine();

                bool isFinished = proc0.WaitForExit(60000);   // Wait up to a minute for the workflow tests to finish.
                Assert.True(isFinished, String.Format("python {0} in {1} timed out", proc0.StartInfo.Arguments, outputDirectory));

                proc0.Refresh();

                if (0 != proc0.ExitCode)
                {
                    Console.WriteLine("Process exit code: {0}",
                                      proc0.ExitCode);
                }
                Assert.True(0 == proc0.ExitCode, "Testbench run failed: " + output.ToString() + "  " + outputDirectory + "  " + File.ReadAllText(Path.Combine(outputDirectory, "testbench_manifest.json")));    // Check that the job finished OK.
            }

            // Check that files were created in the output path.
            string[] createdFileNames =
            {
                "schema.boardoutline.ger",
                "schema.boardoutline.gpi",
                "schema.bottomlayer.ger",
                "schema.bottomlayer.gpi",
                "schema.bottomsilkscreen.ger",
                "schema.bottomsilkscreen.gpi",
                "schema.bottomsoldermask.ger",
                "schema.bottomsoldermask.gpi",
                "schema.drills.dri",
                "schema.drills.xln",
                "schema.tcream.ger",
                "schema.tcream.gpi",
                "schema.toplayer.ger",
                "schema.toplayer.gpi",
                "schema.topsoldermask.ger",
                "schema.topsoldermask.gpi",
                "schema_centroids.csv",
                "schema.XYRS",  // MOT-743
                "assemblyBom.csv"
            };

            foreach (string filename in createdFileNames)
            {
                var pathOutputFile = Path.Combine(outputDirectory, filename);
                Assert.True(File.Exists(pathOutputFile));
                var fileText = File.ReadAllText(pathOutputFile);
                Assert.False(String.IsNullOrWhiteSpace(fileText));
            }
        }
        public static string HtmlStringToPdfFile(string pdfOutputLocation, string outputFilename, string htmlData, string pdfHtmlToPdfExePath)
        {
            System.IO.StreamWriter stdin;
            try
            {
                //Determine inputs
                if (string.IsNullOrEmpty(htmlData))
                {
                    //log.Info("No input string is provided for HtmlToPdf.");
                    throw new Exception("No input string is provided for HtmlToPdf");
                }

                // string outputFolder = pdfOutputLocation;
                //log.Info("pdf Generation initiated.");

                var p = new System.Diagnostics.Process()
                {
                    StartInfo =
                    {
                        FileName               = AppProperties.BasePhysicalPath + pdfHtmlToPdfExePath,
                        Arguments              = "-q -n - " + outputFilename,
                        UseShellExecute        = false, // needs to be false in order to redirect output
                        CreateNoWindow         = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        RedirectStandardInput  = true, // redirect all 3, as it should be all 3 or none
                        WorkingDirectory       = AppProperties.BasePhysicalPath + pdfOutputLocation
                    }
                };
                p.Start();
                //log.Info("pdf Generation Started.");

                stdin           = new StreamWriter(p.StandardInput.BaseStream, Encoding.UTF8);
                stdin.AutoFlush = true;
                stdin.Write(htmlData);
                stdin.Close();
                //log.Info("pdf Generated.");

                // read the output here...
                var output      = p.StandardOutput.ReadToEnd();
                var errorOutput = p.StandardError.ReadToEnd();

                // ...then wait n milliseconds for exit (as after exit, it can't read the output)
                p.WaitForExit(60000);

                // read the exit code, close process
                int returnCode = p.ExitCode;
                p.Close();
                p.Dispose();
                p.Refresh();
                // if 0 or 2, it worked so return path of pdf
                if ((returnCode == 0) || (returnCode == 2))
                {
                    return(outputFilename);
                }
                else
                {
                    throw new Exception(errorOutput);
                }
            }
            catch (Exception exc)
            {
                //log.Info("Problem generating PDF from HTML string." + exc.Message);

                throw new Exception("Problem generating PDF from HTML string, outputFilename: " + outputFilename, exc);
            }
        }
Example #28
0
 /// <summary>
 /// Execution thread method.
 /// </summary>
 protected void ExecThread()
 {
     while (m_QueueNotEmpty.WaitOne())
     {
         while (m_Queue.Count > 0)
         {
             SySal.OperaDb.OperaDbCredentials cred = new SySal.OperaDb.OperaDbCredentials();
             DataProcessingBatchDesc          desc = null;
             System.Exception retX    = null;
             string           retXstr = "";
             m_ExecProc = new System.Diagnostics.Process();
             lock (m_ExecProc)
             {
                 m_ExecProcKilled = false;
                 lock (m_Queue)
                 {
                     desc = (DataProcessingBatchDesc)m_Queue[0];
                 }
                 m_ExecProc.StartInfo.Arguments             = desc.CommandLineArguments;
                 m_ExecProc.StartInfo.FileName              = desc.Filename;
                 m_ExecProc.StartInfo.UseShellExecute       = false;
                 m_ExecProc.StartInfo.RedirectStandardError = true;
                 desc.Started = desc.Finished = System.DateTime.Now;
                 try
                 {
                     cred.DBUserName    = (desc.AliasUsername == null) ? "" : desc.AliasUsername;
                     cred.DBPassword    = (desc.AliasPassword == null) ? "" : desc.AliasPassword;
                     cred.DBServer      = OperaDataProcessingServer.DBServer;
                     cred.OPERAUserName = (desc.Username == null) ? "" : desc.Username;
                     cred.OPERAPassword = (desc.Password == null) ? "" : desc.Password;
                     cred.RecordToEnvironment(m_ExecProc.StartInfo.EnvironmentVariables);
                     desc.Started = System.DateTime.Now;
                     m_ExecProc.Start();
                 }
                 catch (Exception x)
                 {
                     retX = new DataProcessingException("Internal error occurred during process start.", x);
                 }
                 try
                 {
                     m_ExecProc.PriorityClass = OperaDataProcessingServer.LowPriority ? System.Diagnostics.ProcessPriorityClass.BelowNormal : System.Diagnostics.ProcessPriorityClass.Normal;
                     //m_ExecProc.MaxWorkingSet = new System.IntPtr(OperaDataProcessingServer.PeakWorkingSetMB * 1048576);
                 }
                 catch (Exception) { }
             }
             if (retX == null)
             {
                 //do
                 {
                     try
                     {
                         m_ExecProc.Refresh();
                         retXstr += m_ExecProc.StandardError.ReadToEnd();
                         desc.TotalProcessorTime    = m_ExecProc.TotalProcessorTime;
                         desc.PeakVirtualMemorySize = m_ExecProc.PeakVirtualMemorySize;
                         desc.PeakWorkingSet        = m_ExecProc.PeakWorkingSet;
                     }
                     catch (Exception) {}
                 }
                 //while (m_ExecProc.WaitForExit(1000) == false);
                 desc.Finished = System.DateTime.Now;
                 lock (m_ExecProc)
                 {                        /*
                                           *     try
                                           *     {
                                           *             retXstr += m_ExecProc.StandardError.ReadToEnd();
                                           *     }
                                           *     catch (Exception) {}*/
                     if (retXstr == null || retXstr.Length == 0)
                     {
                         retX = null;
                     }
                     else
                     {
                         retX = new DataProcessingException(retXstr);
                     }
                     if (m_ExecProcKilled)
                     {
                         retX = new Exception("Process has been killed.");
                     }
                 }
             }
             else
             {
                 try
                 {
                     retXstr += m_ExecProc.StandardError.ReadToEnd();
                 }
                 catch (Exception) {}
             }
             m_ExecProc = null;
             SySal.OperaDb.OperaDbConnection conn = null;
             lock (m_ResultList)
                 lock (m_Queue)
                 {
                     DataProcessingResult dpr = new DataProcessingResult(desc, m_ResultLiveTime);
                     dpr.Processed = true;
                     dpr.X         = retX;
                     m_ResultList.Add(dpr);
                     m_Queue.RemoveAt(0);
                 }
         }
     }
 }
Example #29
0
        private void DeployProject(Project proj, IOutputWindow outputWindow, System.Array selectedItems, bool bCreateBat)
        {
            Microsoft.DataWarehouse.Interfaces.IConfigurationSettings settings = (Microsoft.DataWarehouse.Interfaces.IConfigurationSettings)((System.IServiceProvider)proj).GetService(typeof(Microsoft.DataWarehouse.Interfaces.IConfigurationSettings));
            DataWarehouseProjectManager projectManager = (DataWarehouseProjectManager)settings.GetType().InvokeMember("ProjectManager", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.FlattenHierarchy, null, settings, null);

            StringBuilder sBatFileContents = new StringBuilder();
            try
            {
                string sConfigFileName = ((Microsoft.DataWarehouse.VsIntegration.Shell.Project.Extensibility.ProjectExt)proj).FullName + ".bidsHelper.user";
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                if (System.IO.File.Exists(sConfigFileName))
                {
                    doc.Load(sConfigFileName);
                }

#if SQL2014
                //refreshes the cached target version which is needed in GetPathToDtsExecutable below
                SSISHelpers.ProjectTargetVersion? projectTargetVersion = SSISHelpers.GetProjectTargetVersion(proj);
#endif

                IProjectConfiguration config = projectManager.ConfigurationManager.CurrentConfiguration;
                DtsProjectExtendedConfigurationOptions newOptions = new DtsProjectExtendedConfigurationOptions();
                LoadFromBidsHelperConfiguration(doc, config.DisplayName, newOptions);

                //print out header in output window
                if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                {
                    if (string.IsNullOrEmpty(newOptions.FilePath))
                    {
                        outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, "Deployment FilePath is not set. Right click on the project node and set the FilePath property.");
                        return;
                    }
                    outputWindow.ReportStatusMessage("Deploying to file path " + newOptions.FilePath + "\r\n");
                }
                else
                {
                    if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreMsdbDestination)
                    {
                        outputWindow.ReportStatusMessage("Deploying to SSIS Package Store MSDB on server " + newOptions.DestinationServer);
                    }
                    else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreFileSystemDestination)
                    {
                        outputWindow.ReportStatusMessage("Deploying to SSIS Package Store File System on server " + newOptions.DestinationServer);
                    }
                    else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SqlServerDestination)
                    {
                        outputWindow.ReportStatusMessage("Deploying to SQL Server MSDB on server: " + newOptions.DestinationServer);
                    }
                    if (!string.IsNullOrEmpty(newOptions.DestinationFolder))
                        outputWindow.ReportStatusMessage("Deploying to folder: " + newOptions.DestinationFolder);
                    outputWindow.ReportStatusMessage(string.Empty);
                }
                System.Windows.Forms.Application.DoEvents();

                //determine destination types and folders
                string sDestFolder = newOptions.DestinationFolder;
                sDestFolder = sDestFolder.Replace("/", "\\");
                if (!string.IsNullOrEmpty(sDestFolder) && !sDestFolder.EndsWith("\\")) sDestFolder += "\\";
                while (sDestFolder.StartsWith("\\"))
                    sDestFolder = sDestFolder.Substring(1);

                string sDestType = "SQL";
                if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreFileSystemDestination)
                {
                    sDestFolder = "File System\\" + sDestFolder;
                    sDestType = "DTS";
                }
                else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.SsisPackageStoreMsdbDestination)
                {
                    sDestFolder = "MSDB\\" + sDestFolder;
                    sDestType = "DTS";
                }
                else if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                {
                    string sDestinationPath = newOptions.FilePath;
                    if (!sDestinationPath.EndsWith("\\")) sDestinationPath += "\\";
                    if (!System.IO.Directory.Exists(sDestinationPath))
                        System.IO.Directory.CreateDirectory(sDestinationPath);
                    sDestFolder = sDestinationPath;
                    sBatFileContents.Append("mkdir \"").Append(sDestFolder).AppendLine("\"");
                }

                //setup Process object to call the dtutil EXE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.FileName = SSIS.PerformanceVisualization.PerformanceTab.GetPathToDtsExecutable("dtutil.exe", false); //makes the bat file less portable, but does workaround the problem if SSIS2005 and SSIS2008 are both installed... issue 21074

                if (newOptions.DeploymentType != DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                {
                    //create the directories
                    string sAccumulatingDir = "";
                    try
                    {
                        foreach (string dir in sDestFolder.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (!(string.IsNullOrEmpty(sAccumulatingDir) && sDestType == "DTS"))
                            {
                                process.StartInfo.Arguments = string.Format("/FCreate {0};{1};\"{2}\" /SourceServer {3} ", sDestType, (sAccumulatingDir == "" ? "\\" : "\"" + sAccumulatingDir + "\""), dir, newOptions.DestinationServer);
                                sBatFileContents.Append("\"").Append(process.StartInfo.FileName).Append("\" ").AppendLine(process.StartInfo.Arguments);
                                process.Start();
                                process.WaitForExit();
                            }
                            if (!string.IsNullOrEmpty(sAccumulatingDir))
                                sAccumulatingDir += "\\";
                            sAccumulatingDir += dir;
                        }
                    }
                    catch { }
                }

                //loop through each package to deploy
                foreach (object selected in selectedItems)
                {
                    ProjectItem pi;
                    string sFileName;
                    string sFilePath;
                    if (selected is ProjectItem)
                    {
                        pi = (ProjectItem)selected;
                    }
                    else if (selected is UIHierarchyItem && ((UIHierarchyItem)selected).Object is ProjectItem)
                    {
                        pi = ((ProjectItem)((UIHierarchyItem)selected).Object);
                    }
                    else
                    {
                        continue;
                    }
                    sFileName = pi.Name;
                    sFilePath = pi.get_FileNames(0);
                    if (!sFileName.ToLower().EndsWith(".dtsx")) continue;

                    if (pi.Document != null && !pi.Document.Saved)
                    {
                        pi.Save("");
                    }

                    if (newOptions.DeploymentType == DtsProjectExtendedConfigurationOptions.DeploymentTypes.FilePathDestination)
                    {
                        string sDestinationPath = sDestFolder + sFileName;
                        if (System.IO.File.Exists(sDestinationPath))
                        {
                            System.IO.File.SetAttributes(sDestinationPath, System.IO.FileAttributes.Normal);
                        }
                        sBatFileContents.Append("xcopy \"").Append(sFilePath).Append("\" \"").Append(sDestFolder).AppendLine("\" /Y /R");
                        System.IO.File.Copy(sFilePath, sDestinationPath, true);
                        outputWindow.ReportStatusMessage("Deployed " + sFileName);
                    }
                    else
                    {
                        process.Refresh();
                        process.StartInfo.Arguments = string.Format("/FILE \"{0}\" /DestServer {1} /COPY {2};\"{3}\" /Q", sFilePath, newOptions.DestinationServer, sDestType, sDestFolder + sFileName.Substring(0, sFileName.Length - ".dtsx".Length));
                        sBatFileContents.Append("\"").Append(process.StartInfo.FileName).Append("\" ").AppendLine(process.StartInfo.Arguments);
                        process.Start();
                        string sError = process.StandardError.ReadToEnd();
                        string sStandardOutput = process.StandardOutput.ReadToEnd();
                        process.WaitForExit();
                        if (process.ExitCode > 0)
                        {
                            outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, "BIDS Helper encountered an error when deploying package " + sFileName + "!\r\n\"" + process.StartInfo.FileName + "\" " + process.StartInfo.Arguments + "\r\nexit code = " + process.ExitCode + "\r\n" + sStandardOutput);
                            this.ApplicationObject.ToolWindows.OutputWindow.Parent.AutoHides = false; //pin the window open so you can see the problem
                            return;
                        }
                        outputWindow.ReportStatusMessage("Deployed " + sFileName);
                        System.Windows.Forms.Application.DoEvents();
                    }
                }
                outputWindow.ReportStatusMessage("BIDS Helper completed deploying packages successfully.");

                if (bCreateBat)
                {
                    string sBatFilename = System.IO.Path.GetDirectoryName(((Microsoft.DataWarehouse.VsIntegration.Shell.Project.Extensibility.ProjectExt)proj).FullName);
                    sBatFilename += "\\" + newOptions.OutputPath;
                    if (!System.IO.Directory.Exists(sBatFilename))
                        System.IO.Directory.CreateDirectory(sBatFilename);
                    sBatFilename += "\\bidsHelperDeployPackages.bat";
                    if (System.IO.File.Exists(sBatFilename))
                    {
                        System.IO.File.SetAttributes(sBatFilename, System.IO.FileAttributes.Normal);
                    }
                    System.IO.File.WriteAllText(sBatFilename, sBatFileContents.ToString());
                    outputWindow.ReportStatusMessage("Deployment commands saved to: " + sBatFilename + "\r\n\r\n");
                }
            }
            catch (Exception ex)
            {
                outputWindow.ReportStatusError(OutputWindowErrorSeverity.Error, "BIDS Helper encountered an error when deploying packages:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                this.ApplicationObject.ToolWindows.OutputWindow.Parent.AutoHides = false; //pin the window open so you can see the problem
            }
        }
Example #30
0
 public void StudentExceltoDB() // 엑셀로 학생 등록하기
 {
     try
     {
         CommonOpenFileDialog dialog = new CommonOpenFileDialog();
         if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
         {
             Excel.Application excelApp  = new Excel.Application();
             Excel.Workbook    workBook  = excelApp.Workbooks.Open(dialog.FileName);
             Excel.Worksheet   workSheet = workBook.Worksheets.get_Item(1) as Excel.Worksheet;
             Excel.Range       range     = workSheet.UsedRange; // 사용중인 셀 범위를 가져오기
             List <string>     fail      = new List <string>();
             List <string>     success   = new List <string>();
             if (!(range.Columns.Count == 5)) // 데이터 적정성 검사
             {
                 throw new Exception("데이터 형식 오류");
             }
             for (int row = 1; row <= range.Rows.Count; row++) // 가져온 행 만큼 반복
             {
                 List <string> student = new List <string>();
                 for (int column = 1; column <= range.Columns.Count; column++) // 가져온 열 만큼 반복
                 {
                     student.Add(Convert.ToString((range.Cells[row, column] as Excel.Range).Value2));
                 }
                 if (student[4] == "이름") // 타이틀인 경우
                 {
                     continue;
                 }
                 if (!InsertStudent(student.ToArray()))
                 {
                     fail.Add(string.Join("/", student) + " 등록실패\n");
                 }
                 else
                 {
                     success.Add(string.Join("/", student) + " 등록성공\n");
                 }
             }
             if (fail.Count != 0)
             {
                 MessageBox.Show(string.Join("", fail));
             }
             if (success.Count != 0)
             {
                 MessageBox.Show(string.Join("", success));
             }
             workBook.Close(true);
             GetWindowThreadProcessId(new IntPtr(excelApp.Hwnd), out uint processId);
             excelApp.Quit();
             if (processId != 0)
             {
                 System.Diagnostics.Process excelProcess = System.Diagnostics.Process.GetProcessById((int)processId);
                 excelProcess.CloseMainWindow();
                 excelProcess.Refresh();
                 excelProcess.Kill();
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Example #31
0
        /// <summary>
        /// 同步功能菜单
        /// </summary>
        public void MenuSyncFunction(KJRichTextBox _RtxtSysMsg)
        {
            if (frmMain.commType)
            {
                if (StartTcp.m_TcpClientPort != null)
                {
                    ToolStripMenuItem menuItemSerialPortPause = new ToolStripMenuItem("环网发送暂停");

                    menuItemSerialPortPause.Click += delegate(object sender, EventArgs e)
                    {
                        if (StartTcp.m_TcpClientPort.IsPause)
                        {
                            ((ToolStripMenuItem)(sender)).Text = "环网发送暂停";
                        }
                        else
                        {
                            ((ToolStripMenuItem)(sender)).Text = "环网继续发送";
                        }

                        StartTcp.m_TcpClientPort.IsPause = !StartTcp.m_TcpClientPort.IsPause;
                        if (StartTcp.m_TcpClientPort.IsPause == false)
                        {
                            StartTcp.m_TcpClientPort.SendCmd();
                        }
                    };
                    menuItemPause.DropDownItems.Add(menuItemSerialPortPause);
                }
            }
            else
            {
                // 暂停子菜单
                if (StartPort.s_serialPort != null)
                {
                    ToolStripMenuItem[] menuItemSerialPortPause = new ToolStripMenuItem[StartPort.s_serialPort.Length];
                    for (int i = 0; i < StartPort.s_serialPort.Length; i++)
                    {
                        menuItemSerialPortPause[i] = new ToolStripMenuItem(StartPort.s_serialPort[i].PortName + " 发送暂停");
                        menuItemSerialPortPause[i].Tag = i;
                        menuItemSerialPortPause[i].Click += delegate(object sender, EventArgs e)
                        {
                            if (StartPort.s_serialPort[int.Parse(((ToolStripMenuItem)(sender)).Tag.ToString())].IsPause)
                            {
                                ((ToolStripMenuItem)(sender)).Text = StartPort.s_serialPort[int.Parse(((ToolStripMenuItem)(sender)).Tag.ToString())].PortName + " 发送暂停";
                            }
                            else
                            {
                                ((ToolStripMenuItem)(sender)).Text = StartPort.s_serialPort[int.Parse(((ToolStripMenuItem)(sender)).Tag.ToString())].PortName + " 继续发送";
                            }

                            StartPort.s_serialPort[int.Parse(((ToolStripMenuItem)(sender)).Tag.ToString())].IsPause = !StartPort.s_serialPort[int.Parse(((ToolStripMenuItem)(sender)).Tag.ToString())].IsPause;
                            if (StartPort.s_serialPort[int.Parse(((ToolStripMenuItem)(sender)).Tag.ToString())].IsPause == false)
                            {
                                StartPort.s_serialPort[int.Parse(((ToolStripMenuItem)(sender)).Tag.ToString())].SendCmd();
                            }
                        };
                        menuItemPause.DropDownItems.Add(menuItemSerialPortPause[i]);
                    }
                }
            }

            // 启动应用程序
            menuItemDataCopy.Click += delegate
            {

                string strTran = string.Empty;  // 需要传送的内容
                bool blnNotepad = false;         // 记事本成功启动

                #region [ 启动记事本 ]

                System.Diagnostics.Process Proc;

                try
                {
                    // 启动记事本
                    Proc = new System.Diagnostics.Process();
                    Proc.StartInfo.FileName = "notepad.exe";
                    Proc.StartInfo.UseShellExecute = false;
                    Proc.StartInfo.RedirectStandardInput = true;
                    Proc.StartInfo.RedirectStandardOutput = true;

                    Proc.Start();

                    blnNotepad = true;
                }
                catch
                {
                    Proc = null;
                }

                #endregion

                #region [ 系统消息面板 ]

                if (_RtxtSysMsg != null)
                {
                    // 如果记事本启动成功,则将系统消息面板中的数据提交给记事本,否则发送到内存中。
                    if (blnNotepad)
                    {
                        strTran = _RtxtSysMsg.Text.Replace("\n", "\r\n");
                    }
                    else
                    {
                        _RtxtSysMsg.SelectAll();
                        _RtxtSysMsg.Copy();
                    }
                }

                #endregion

                #region [ 数据面板 ]
                if (frmMain.commType)
                {
                    // 如果记事本启动成功,则将数据面板中的数据提交给记事本,否则发送到内存中。
                    if (StartTcp.m_TcpClientPort.RTxtMsg != null)
                    {
                        if (StartTcp.m_TcpClientPort.RTxtMsg.Focused)
                        {
                            if (blnNotepad)
                            {
                                strTran = StartTcp.m_TcpClientPort.RTxtMsg.Text.Replace("\n", "\r\n");
                            }
                            else
                            {
                                StartTcp.m_TcpClientPort.RTxtMsg.SelectAll();
                                StartTcp.m_TcpClientPort.RTxtMsg.Copy();
                            }

                        }
                    }

                    if (StartTcp.m_TcpClientPort.RTxtMsgc != null)
                    {
                        if (StartTcp.m_TcpClientPort.RTxtMsgc.Focused)
                        {
                            if (blnNotepad)
                            {
                                strTran = StartTcp.m_TcpClientPort.RTxtMsgc.Text.Replace("\n", "\r\n");
                            }
                            else
                            {
                                StartTcp.m_TcpClientPort.RTxtMsgc.SelectAll();
                                StartTcp.m_TcpClientPort.RTxtMsgc.Copy();
                            }

                        }
                    }

                    if (StartTcp.m_TcpClientPort.RTxtMsge != null)
                    {
                        if (StartTcp.m_TcpClientPort.RTxtMsge.Focused)
                        {
                            if (blnNotepad)
                            {
                                strTran = StartTcp.m_TcpClientPort.RTxtMsge.Text.Replace("\n", "\r\n");
                            }
                            else
                            {
                                StartTcp.m_TcpClientPort.RTxtMsge.SelectAll();
                                StartTcp.m_TcpClientPort.RTxtMsge.Copy();
                            }

                        }
                    }

                    if (StartTcp.m_TcpClientPort.RTxtMsgo != null)
                    {
                        if (StartTcp.m_TcpClientPort.RTxtMsgo.Focused)
                        {
                            if (blnNotepad)
                            {
                                strTran = StartTcp.m_TcpClientPort.RTxtMsgo.Text.Replace("\n", "\r\n");
                            }
                            else
                            {
                                StartTcp.m_TcpClientPort.RTxtMsgo.SelectAll();
                                StartTcp.m_TcpClientPort.RTxtMsgo.Copy();
                            }

                        }
                    }
                }
                else
                {
                    // 如果记事本启动成功,则将数据面板中的数据提交给记事本,否则发送到内存中。
                    for (int i = 0; i < StartPort.s_serialPort.Length; i++)
                    {
                        if (StartPort.s_serialPort[i].RTxtMsg != null)
                        {
                            if (StartPort.s_serialPort[i].RTxtMsg.Focused)
                            {
                                if (blnNotepad)
                                {
                                    strTran = StartPort.s_serialPort[i].RTxtMsg.Text.Replace("\n", "\r\n");
                                }
                                else
                                {
                                    StartPort.s_serialPort[i].RTxtMsg.SelectAll();
                                    StartPort.s_serialPort[i].RTxtMsg.Copy();
                                }
                                break;
                            }
                        }

                        if (StartPort.s_serialPort[i].RTxtMsgc != null)
                        {
                            if (StartPort.s_serialPort[i].RTxtMsgc.Focused)
                            {
                                if (blnNotepad)
                                {
                                    strTran = StartPort.s_serialPort[i].RTxtMsgc.Text.Replace("\n", "\r\n");
                                }
                                else
                                {
                                    StartPort.s_serialPort[i].RTxtMsgc.SelectAll();
                                    StartPort.s_serialPort[i].RTxtMsgc.Copy();
                                }
                                break;
                            }
                        }

                        if (StartPort.s_serialPort[i].RTxtMsge != null)
                        {
                            if (StartPort.s_serialPort[i].RTxtMsge.Focused)
                            {
                                if (blnNotepad)
                                {
                                    strTran = StartPort.s_serialPort[i].RTxtMsge.Text.Replace("\n", "\r\n");
                                }
                                else
                                {
                                    StartPort.s_serialPort[i].RTxtMsge.SelectAll();
                                    StartPort.s_serialPort[i].RTxtMsge.Copy();
                                }
                                break;
                            }
                        }

                        if (StartPort.s_serialPort[i].RTxtMsgo != null)
                        {
                            if (StartPort.s_serialPort[i].RTxtMsgo.Focused)
                            {
                                if (blnNotepad)
                                {
                                    strTran = StartPort.s_serialPort[i].RTxtMsgo.Text.Replace("\n", "\r\n");
                                }
                                else
                                {
                                    StartPort.s_serialPort[i].RTxtMsgo.SelectAll();
                                    StartPort.s_serialPort[i].RTxtMsgo.Copy();
                                }
                                break;
                            }
                        }
                    }
                }
                #endregion

                #region [ 传递数据给记事本 ]

                if (blnNotepad && Proc != null)
                {
                    // 调用 API, 传递数据
                    while (Proc.MainWindowHandle == IntPtr.Zero)
                    {
                        Proc.Refresh();
                    }

                    IntPtr vHandle = FindWindowEx(Proc.MainWindowHandle, IntPtr.Zero, "Edit", null);

                    // 传递数据给记事本
                    SendMessage(vHandle, WM_SETTEXT, 0, strTran);
                }

                #endregion

            };
        }
Example #32
0
        /// <summary>
        /// 用记事本打开文件路径或内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="strContext"></param>
        public static void OpenEdit(String filePath, String strContext)
        {
            #region 启动 notepad++

            System.Diagnostics.Process ProcNotePad = null;

            List <String> programFolderList = new List <String>();
            //programFolderList.Add(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
            //if (Environment.Is64BitOperatingSystem)
            //    programFolderList.Add(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86));
            programFolderList.Add("C:\\Program Files");
            programFolderList.Add("C:\\Program Files (x86)");

            foreach (String programFolder in programFolderList)
            {
                if (String.IsNullOrWhiteSpace(programFolder))
                {
                    continue;
                }

                String notePadPath = Path.Combine(programFolder, "Notepad++", "notepad++.exe");

                if (File.Exists(notePadPath))
                {
                    try
                    {
                        ProcNotePad = new System.Diagnostics.Process();
                        ProcNotePad.StartInfo.FileName               = notePadPath;
                        ProcNotePad.StartInfo.Arguments              = filePath;
                        ProcNotePad.StartInfo.UseShellExecute        = true;
                        ProcNotePad.StartInfo.RedirectStandardInput  = false;
                        ProcNotePad.StartInfo.RedirectStandardOutput = false;

                        ProcNotePad.Start();
                        return;
                    }
                    catch
                    {
                        ProcNotePad = null;
                    }
                }
            }
            #endregion

            if (ProcNotePad == null)
            {
                #region [ 启动记事本 ]

                System.Diagnostics.Process Proc;

                try
                {
                    // 启动记事本
                    Proc = new System.Diagnostics.Process();
                    Proc.StartInfo.FileName               = "notepad.exe";
                    Proc.StartInfo.UseShellExecute        = false;
                    Proc.StartInfo.RedirectStandardInput  = true;
                    Proc.StartInfo.RedirectStandardOutput = true;

                    Proc.Start();
                }
                catch
                {
                    Proc = null;
                }

                #endregion

                #region [ 传递数据给记事本 ]

                if (Proc != null)
                {
                    // 调用 API, 传递数据
                    while (Proc.MainWindowHandle == IntPtr.Zero)
                    {
                        Proc.Refresh();
                    }

                    IntPtr vHandle = Win32API.FindWindowEx(Proc.MainWindowHandle, IntPtr.Zero, "Edit", null);

                    // 传递数据给记事本
                    Win32API.SendMessage(vHandle, Win32API.WM_SETTEXT, 0, strContext);
                }
                else
                {
                    LogForm form = new LogForm(strContext);
                    form.ShowDialog();
                }

                #endregion
            }
        }
Example #33
0
        private void gMake32_Click(object sender, EventArgs e)
        {
            string fo = Application.ExecutablePath;
            using (System.IO.FileStream i = new System.IO.FileStream(fo, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                fo = fo.Substring(0, fo.LastIndexOf('.')) + "32.exe";
                using (System.IO.FileStream o = new System.IO.FileStream(fo, System.IO.FileMode.Create))
                {
                    bool first = true;
                    byte[] buf = new byte[8192];
                    while (true)
                    {
                        int n = i.Read(buf, 0, buf.Length);
                        if (first)
                        {
                            first = false;
                            buf[0x218] = 3; //1=any
                        }
                        if (n <= 0) break;
                        o.Write(buf, 0, n);
                    }
                }
            }
            System.Diagnostics.Process rs = new System.Diagnostics.Process();
            rs.StartInfo.FileName = "Loopstream32.exe";
            rs.StartInfo.Arguments = "sign";
            rs.Start();
            Application.DoEvents();
            rs.Refresh();
            while (!rs.HasExited)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(10);
            }
            for (int a = 0; a < 10; a++)
            {
                try
                {
                    System.IO.File.Delete("Loopstream32.exe");
                    System.IO.File.Move("Loopstream32.exe.exe", "Loopstream32.exe");
                    break;
                }
                catch { }
                System.Threading.Thread.Sleep(100);
            }

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = "Loopstream32.exe";
            proc.Start();
            proc.Refresh();
            Program.kill();
        }
Example #34
0
        public bool Convert(string src, string tar)
        {
            bool        result      = false;
            Application application = null;
            Workbook    workBook    = null;

            try
            {
                application = new Application( );
                workBook    = application.Workbooks.Open(Path.Combine(Directory.GetCurrentDirectory( ), src.Substring(2)));
                string table = "";

                for (int i = 1; i <= workBook.Worksheets.Count; ++i)
                {
                    Worksheet workSheet = workBook.Worksheets.Item[i];
                    if (workSheet.Name.Contains(Exepctional))        // #가 포함일 경우 제외
                    {
                        continue;
                    }
                    Range range = workSheet.UsedRange;

                    table += string.Format("//{0}\n", workSheet.Name);
                    for (int row = 1; row <= range.Rows.Count; ++row)
                    {
                        for (int column = 1; column <= range.Columns.Count; ++column)
                        {
                            Range  check  = (range.Cells[column][2] as Range);
                            string design = string.Format("{0}", check.Value2);
                            if (design.Contains(IgnoreString))        // design열 제외
                            {
                                continue;
                            }

                            Range r = (range.Cells[column][row] as Range);
                            table += string.Format("{0}", r.Value2);
                            if (column < range.Columns.Count)
                            {
                                table += ",";
                            }
                        }
                        table  = System.Text.RegularExpressions.Regex.Replace(table, ",*$", "");
                        table += "\n";
                    }
                    table += "\n";
                }

                string       output = tar;
                StreamWriter csv    = new StreamWriter(@output, false);
                csv.Write(table);
                csv.Close( );


                result = true;
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
            finally
            {
                workBook.Close(true);

                uint processId = 0;
                GetWindowThreadProcessId(new IntPtr(application.Hwnd), out processId);
                application.Quit( );
                if (processId != 0)
                {
                    System.Diagnostics.Process excelProcess = System.Diagnostics.Process.GetProcessById((int)processId);
                    excelProcess.CloseMainWindow( );
                    excelProcess.Refresh( );
                    excelProcess.Kill( );
                }
            }

            return(result);
        }
Example #35
0
 public void Refresh()
 {
     _process.Refresh();
 }