Exemple #1
0
        private void metroTile13_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");
            p.WaitForInputIdle();

            //SNativeMethods.SetParent(p.MainWindowHandle, this.Handle);
        }
        /// <summary>
        /// Given an index file, run the indexer to update it.
        /// </summary>
        public static bool UpdateIndexFile(string indexFile)
        {
            bool ok = false;

            try
            {
                //Now build the index file, wait for the index to exit.
                string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
                System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
                //Switch to the Deploy directory if need be, while debugging.
                appDirectory   = appDirectory.Replace("\\CodeXCavator\\bin\\Debug", "\\Deploy");
                appDirectory   = appDirectory.Replace("\\CodeXCavator\\bin\\Release", "\\Deploy");
                pInfo.FileName = appDirectory + "CodeXCavator.Indexer.exe";
                string args = "-autoclose \"" + indexFile + "\"";
                pInfo.Arguments = args;
                System.Diagnostics.Process p = System.Diagnostics.Process.Start(pInfo);
                p.WaitForInputIdle();
                p.WaitForExit();
                ok = true;
            }
            catch (Exception ex)
            {
                //Show if the new file contains an invalid path etc.
                MessageBox.Show(ex.Message);
            }
            return(ok);
        }
        /// <summary>
        /// 调用外部程序,并设定外部程序和主程序并行,并非等待外部程序完成后才继续运行主程序
        /// </summary>
        /// <param name="pParentHandle"></param>
        /// <param name="pExeName"></param>
        public static bool RunExtSub(IntPtr pParentHandle, string pExeName, ref string err)
        {
            try
            {
                err = "";

                if (!System.IO.File.Exists(pExeName))
                {
                    err = "程序" + pExeName + "不存在于指定位置";
                    return(false);
                }

                System.Diagnostics.Process p = System.Diagnostics.Process.Start(@pExeName);
                p.WaitForInputIdle();
                SetParent(p.MainWindowHandle, pParentHandle);
                ShowWindowAsync(p.MainWindowHandle, 3);

                return(true);
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return(false);
            }
        }
        /// <summary>
        /// Construct a <see cref="Process"/>
        /// </summary>
        /// <param name="handle">The value of <see cref="handle"/></param>
        /// <param name="lifetime">The value of <see cref="Lifetime"/></param>
        /// <param name="outputStringBuilder">The value of <see cref="outputStringBuilder"/></param>
        /// <param name="errorStringBuilder">The value of <see cref="errorStringBuilder"/></param>
        /// <param name="combinedStringBuilder">The value of <see cref="combinedStringBuilder"/></param>
        /// <param name="logger">The value of <see cref="logger"/></param>
        /// <param name="preExisting">If <paramref name="handle"/> was NOT just created</param>
        public Process(System.Diagnostics.Process handle, Task <int> lifetime, StringBuilder outputStringBuilder, StringBuilder errorStringBuilder, StringBuilder combinedStringBuilder, ILogger <Process> logger, bool preExisting)
        {
            this.handle = handle ?? throw new ArgumentNullException(nameof(handle));
            Lifetime    = lifetime ?? throw new ArgumentNullException(nameof(lifetime));

            this.outputStringBuilder   = outputStringBuilder;
            this.errorStringBuilder    = errorStringBuilder;
            this.combinedStringBuilder = combinedStringBuilder;

            this.logger = logger ?? throw new ArgumentNullException(nameof(logger));

            Id = handle.Id;

            if (preExisting)
            {
                Startup = Task.CompletedTask;
                return;
            }

            Startup = Task.Factory.StartNew(() =>
            {
                try
                {
                    handle.WaitForInputIdle();
                }
                catch (InvalidOperationException) { }
            }, default, TaskCreationOptions.LongRunning, TaskScheduler.Current);
Exemple #5
0
        public mainForm(com.echo.PartyMemberOM.WebServices.User u)
        {
            curUser = u;
            InitializeComponent();
            AddControls();

            System.Diagnostics.Process p = System.Diagnostics.Process.Start("regsvr32.exe", " /s kdbole6.dll");
            p.WaitForInputIdle();//等待执行注册命令完毕
        }
Exemple #6
0
        private static bool PrintPdf(string filePath, bool bSilently)
        {
            DDEClient client = null;

            try
            {
                client = new DDEClient("acroview", "control");

                client.Open();
            }
            catch
            {
            }

            System.Diagnostics.Process p = null;

            if (!client.Opened)
            {
                try
                {
                    // try running Adobe Reader
                    p = new System.Diagnostics.Process();
                    p.StartInfo.FileName = "AcroRd32.exe";
                    p.Start();
                    p.WaitForInputIdle();
                }
                catch
                {
                    return(false);
                }

                client.Open();

                if (!client.Opened)
                {
                    client.Dispose();

                    return(false);
                }
            }

            bool ret = client.Execute("[DocOpen(\"" + filePath + "\")]", 60000) &&
                       client.Execute((bSilently ? "[FilePrintSilent(\"" : "[FilePrint(\"") + filePath + "\")]", 60000) &&
                       client.Execute("[DocClose(\"" + filePath + "\")]", 60000);

            if (p != null)
            {
                ret = ret && client.Execute("[AppExit]", 60000);

                p.WaitForExit();
            }

            client.Dispose();

            return(ret);
        }
Exemple #7
0
        private void CheckBouyomichan()
        {
            Exception err = null;

            try {
                // TRANSLATORS: Log message. Initializing Rein.
                Logger.Log(T._("  - Check Bouyomi-chan ..."));
                this.bouyomichan.ClearTalkTasks();
                return;
            } catch (Exception e) {
                err = e;
            }
            if (Config.Instance.MainConfig.BouyomichanPath == null || Config.Instance.MainConfig.BouyomichanPath.Length == 0)
            {
                // TRANSLATORS: Error message. Initializing Rein.
                throw new Exception(T._("Could not load Bouyomi-chan. Please check Bouyomi-chan awaking."), err);
            }
            try {
                // TRANSLATORS: Log message. Initializing Rein.
                Logger.Log(T._("  - Executing Bouyomi-chan ..."));
                System.Diagnostics.Process p = System.Diagnostics.Process.Start(Config.Instance.MainConfig.BouyomichanPath);
                var timeout_exec             = 10;
                while (timeout_exec > 0)
                {
                    if (p.WaitForInputIdle(1000))
                    {
                        break;
                    }
                    timeout_exec--;
                }
            } catch (Exception e) {
                // TRANSLATORS: Error message. Initializing Rein.
                throw new Exception(T._("Could not execute Bouyomi-chan."), e);
            }
            // TRANSLATORS: Log message. Initializing Rein.
            Logger.Log(T._("  - Check Bouyomi-chan ..."));
            var timeout = 10;

            while (timeout > 0)
            {
                try {
                    this.bouyomichan.ClearTalkTasks();
                    return;
                } catch (Exception e) {
                    err = e;
                }
                System.Threading.Thread.Sleep(1000);
                timeout--;
            }
            this.Dispose();
            if (err != null)
            {
                // TRANSLATORS: Error message. Initializing Rein.
                throw new Exception(T._("Could not load Bouyomi-chan. Please check Bouyomi-chan awaking."), err);
            }
        }
Exemple #8
0
 private void imageCroppingBox1_MouseDown(object sender, MouseEventArgs e)
 {
     m_ptLastMouseDown = e.Location;
     if (e.Button != MouseButtons.Left)
     {
         return;                                                 //禁止右键的时候触发
     }
     if (!imageCroppingBox1.IsLockSelected)
     {
         this.captureToolbar1.Visible = false;
     }
     if (m_bCtrlDown && !imageCroppingBox1.IsSelected)
     {
         this.Close();
         string strFileName = Application.StartupPath + "/SpyTool.exe";
         if (System.IO.File.Exists(strFileName))
         {
             System.Diagnostics.Process p = new System.Diagnostics.Process();
             p.StartInfo.FileName  = strFileName;
             p.StartInfo.Arguments = String.Format("{0} {1} {2}", m_hWnd, m_bGetVisable, m_bGetTransparent);
             p.Start();
             p.WaitForInputIdle();
             Win32.SetForegroundWindow(p.MainWindowHandle);
         }
         else
         {
             new FrmTextAlert("没有发现[SpyTool.exe]").Show();
         }
     }
     if (m_bAltDown && !imageCroppingBox1.IsSelected)
     {
         if (FrmCapture._ScreenRecorder != null)
         {
             FrmCapture._ScreenRecorder.Dispose();
         }
         FrmCapture._ScreenRecorder              = new ScreenRecorder(m_hWnd, FrmCapture._ScreenRecorderInterval);
         FrmCapture._ScreenRecorder.RecordError += _ScreenRecorder_RecordError;
         new FrmRectAlert(m_rect, "Gif Window").Show();
         this.Close();
     }
     //如果已经锁定了选取 并且 鼠标点下的位置在选取内 而且工具条上有选择工具 那么则表示可能需要绘制了 如:矩形框 箭头 等
     if (imageCroppingBox1.IsLockSelected && imageCroppingBox1.SelectedRectangle.Contains(e.Location) && captureToolbar1.GetSelectBtnName() != null)
     {
         if (captureToolbar1.GetSelectBtnName() == "btn_text")   //如果选择的是文字工具 那么特殊处理
         {
             textBox1.Location = e.Location;                     //将文本框位置设置为鼠标点下的位子
             textBox1.Visible  = true;                           //显示文本框以便输入文字
             textBox1.Focus();                                   //获得焦点
             return;                                             //特殊处理的角色 直接返回
         }
         m_bDrawEffect = true;                                   //设置标识 在MouseMove用于判断当前的操作是否是后期的绘制
         Cursor.Clip   = imageCroppingBox1.SelectedRectangle;    //设置鼠标的活动区域
     }
 }
        /// <summary>
        /// 加载普通 Exe
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoadExe_Click(object sender, EventArgs e)
        {
            // 这里启动外部的  记事本 程序.
            normalP = System.Diagnostics.Process.Start("notepad");

            normalP.WaitForInputIdle();

            // 程序启动后, 放在 pnlExe 的 容器里面。
            SetParent(normalP.MainWindowHandle, this.pnlExe.Handle);

            ShowWindowAsync(normalP.MainWindowHandle, 3);
        }
Exemple #10
0
        public void Wait_Idle()
        {
            if (_running)
            {
                switch (_my_type)
                {
                case Win_Types.CMD:
                    _my_proc.WaitForInputIdle();
                    break;

                case Win_Types.GUI:
                    _my_proc.WaitForInputIdle();
                    break;

                case Win_Types.HTML:
                    break;

                case Win_Types.GDI:
                    break;
                }
            }
        }
Exemple #11
0
 public IActionResult Calc()
 {
     try
     {
         System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");
         p.WaitForInputIdle();
         //NativeMethods.SetParent(p.MainWindowHandle, this.Handle);
         return(Ok("Executado"));
     }
     catch (Exception e)
     {
         return(Forbid(e.Message));
     }
 }
Exemple #12
0
        static void Main(string[] args)
        {
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command\");
            string s     = key.GetValue("").ToString();
            int    index = s.LastIndexOf('.');

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            // Console.WriteLine();
            process.StartInfo.FileName = string.Format(@"{0}", s.Substring(0, index + 4));
            string url = "http://www.baidu.com?java";

            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.Arguments      = string.Format("--new-window --window-size==300*500  --window-position==300,200  \"{0}\"", url);
            process.StartInfo.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Minimized;
            process.Start();
            process.WaitForInputIdle();
            //Console.ReadKey();
        }
Exemple #13
0
        private void HandleServerSpinUpMessage(Guid customerGUID, int worldServerID, int zoneInstanceID, string mapName, int port)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"Starting up {customerGUID} : {worldServerID} : {mapName} : {port}");

            //Security Check on CustomerGUID
            if (_customerGUID != customerGUID)
            {
                Console.WriteLine("HandleServerSpinUpMessage - Incoming CustomerGUID does not match OWSAPIKey in appsettings.json");
                return;
            }

            //string PathToDedicatedServer = "E:\\Program Files\\Epic Games\\UE_4.25\\Engine\\Binaries\\Win64\\UE4Editor.exe";
            //string ServerArguments = "\"C:\\OWS\\OpenWorldStarterPlugin\\OpenWorldStarter.uproject\" {0}?listen -server -log -nosteam -messaging -port={1}";

            System.Diagnostics.Process proc = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    FileName               = _OWSInstanceLauncherOptions.Value.PathToDedicatedServer,
                    Arguments              = Encoding.Default.GetString(Encoding.UTF8.GetBytes(String.Format(_OWSInstanceLauncherOptions.Value.ServerArguments, mapName, port))),
                    UseShellExecute        = false,
                    RedirectStandardOutput = false,
                    CreateNoWindow         = false
                }
            };

            proc.Start();
            proc.WaitForInputIdle();

            _zoneServerProcessesRepository.AddZoneServerProcess(new ZoneServerProcess {
                ZoneInstanceId = zoneInstanceID,
                MapName        = mapName,
                Port           = port,
                ProcessId      = proc.Id,
                ProcessName    = proc.ProcessName
            });

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"{customerGUID} : {worldServerID} : {mapName} : {port} is ready for players");

            //The server has finished spinning up.  Set the status to 2.
            _ = UpdateZoneServerStatusReady(zoneInstanceID);
        }
Exemple #14
0
 public static int Main(string[] args)
 {
     try
     {
         if (args.Count() == 0)
         {
             return(0);
         }
         // ...
         // Wait until the user's desktop is inactive (outside the scope of this solution)
         // ...
         String url = args[0];
         if (CheckAnyExeCertificate(DefaultBrowserPath))
         {
             System.Diagnostics.Process          process   = new System.Diagnostics.Process();
             System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
             startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
             startInfo.FileName    = "cmd.exe";
             // ...
             // Get the path to the default browser from registry, and create a StartupInfo object with it.
             // ...
             process.StartInfo = startInfo;
             process.Start();
             try
             {
                 process.WaitForInputIdle();
             }
             catch (InvalidOperationException)
             {
                 // if the process exited then it passed the URL on to the other browser process.
             }
             String title = GetWebPageTitle(url);
             if (!String.IsNullOrEmpty(title))
             {
                 BringToFront(title);
             }
         }
         return(0);
     }
     catch (System.Exception ex)
     {
         return(-1);
     }
 }
Exemple #15
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);
        }
Exemple #16
0
        public bool AwaitStart(ILogger logger = null, TimeSpan timeout = default(TimeSpan))
        {
            if (m_state == TaskExecutionState.Started)
            {
                DateTime entryTime = DateTime.UtcNow;

                this.SetState(TaskExecutionState.AwaitingStartCondition);

                if (m_process.WaitForInputIdle((int)timeout.TotalMilliseconds))
                {
                    this.SetState(TaskExecutionState.Running);
                }
                else
                {
                    this.SetState(TaskExecutionState.Started);
                    return(false);
                }



                this.ForceRefresh();

                while (m_process.MainWindowHandle == IntPtr.Zero)
                {
                    //context.Log("Waiting for started process to open a main window.");

                    TimeSpan time = DateTime.UtcNow - entryTime;
                    if (time > timeout)
                    {
                        //context.ReportFailureOrError(new TimeoutWaitingForInputIdleError(), String.Format("Process did not open a main window in {0} seconds.", timeout));
                        break;
                    }
                    System.Threading.Thread.Sleep(100);
                    m_process.Refresh();
                }
            }
            else
            {
                throw new Exception("Process is not in the right state (" + m_state.ToString() + ") for an 'AwaitStart' operation.");
            }
            return(false);
        }
Exemple #17
0
 private bool PrepareForWebRecording()
 {
     System.Diagnostics.Process[] ieProcesses = System.Diagnostics.Process.GetProcessesByName("iexplore");
     if (ieProcesses.Length > 0)
     {
         DialogResult result = MessageBox.Show("Internet explorer is open on your machine, and need to be closed.\nDo you want to close it (choosing No will cancel your recording) ?",
                                               "Close Internet Explorer ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
         if (result == DialogResult.No)
         {
             return(false);
         }
         foreach (System.Diagnostics.Process ieProcess in ieProcesses)
         {
             ieProcess.Kill();
             ieProcess.WaitForExit(30000);
         }
     }
     System.Diagnostics.Process testedProcess = System.Diagnostics.Process.Start("iexplore", RecorderConfig.Default.WebStartURL);
     testedProcess.WaitForInputIdle();
     return(true);
 }
Exemple #18
0
        public static void PrintPDF(string path)
        {
            string printerPath = "";
            PrintDialog pd = new PrintDialog();
            var result = pd.ShowDialog();
            if (result == DialogResult.OK)
            {
                printerPath = pd.PrinterSettings.PrinterName;
            }

            //string printer = GetDefaultPrinter();
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = path;
            process.StartInfo.Verb = "printto";
            process.StartInfo.Arguments = "\"" + printerPath + "\"";

            process.Start();

            // I have to use this in case of Adobe Reader to close the window
            process.WaitForInputIdle();
            process.Kill();
        }
Exemple #19
0
        /// <summary>
        // 填充组织树(初始),含根节点和跟节点的子节点
        /// </summary>
        private void FillOrg()
        {
            try
            {
                D01TableAdapter.FillByTopOrg(XT2007DataSet.D01);

                TreeNode root = null;
                if (XT2007DataSet.D01 != null)
                {
                    XT2007DataSet.D01Row r = XT2007DataSet.D01.Rows[0] as XT2007DataSet.D01Row;
                    root             = orgTree.Nodes.Add(r.D0107, r.D0101);                                //增加根组织
                    root.Name        = r.D0107;
                    root.ToolTipText = "(" + r.D0107 + ")" + r.D0101;
                }

                if (root != null)
                {
                    D01TableAdapter.FillByPID(XT2007DataSet.D01, root.Name);

                    if (XT2007DataSet.D01 != null)
                    {
                        foreach (XT2007DataSet.D01Row row in XT2007DataSet.D01)
                        {
                            TreeNode subNode = root.Nodes.Add(row.D0107, row.D0101);
                            subNode.Name        = row.D0107;
                            subNode.ToolTipText = "(" + row.D0107 + ")" + row.D0101;
                        }
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                System.Diagnostics.Process p = System.Diagnostics.Process.Start("regsvr32.exe", " kdbole6.dll");
                p.WaitForInputIdle();//等待执行注册命令完毕
            }
        }
Exemple #20
0
 private void lblCalc_Click(object sender, EventArgs e)
 {
     //Ação click
     System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");
     p.WaitForInputIdle();
 }
Exemple #21
0
 public mainForm()
 {
     InitializeComponent();
     System.Diagnostics.Process p = System.Diagnostics.Process.Start("regsvr32", " /s kdbole6.dll");
     p.WaitForInputIdle();
 }
Exemple #22
0
        private void ConvertToStream(string fileUrl)
        {
            try
            {
                Thread waitThread = new Thread(() =>
                {
                    PleaseWaitWindow wait = new PleaseWaitWindow();

                    wait.ShowDialog();
                    // wait.LoadingAdorner.IsAdornerVisible = true;
                    wait.Close();
                });
                waitThread.SetApartmentState(ApartmentState.STA);
                waitThread.Start();
            }

            catch
            {
            }

            System.Threading.Thread.Sleep(2000);

            try
            {
                //  ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(fileUrl);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();



                var    theStream = new object();
                string fileName  = AppDomain.CurrentDomain.BaseDirectory + "Printings" + @"\toPrint.pdf";


                using (var stream = File.Create(fileName))
                {
                    File.SetAttributes(fileName, FileAttributes.Normal);
                    response.GetResponseStream().CopyTo(stream);
                }

                iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(fileName);
                int numberOfPages = pdfReader.NumberOfPages;

                if (GlobalCounters.numberOfCurrentPrintings + numberOfPages <= Convert.ToInt32("6"))
                {
                    try
                    {
                        // this.log.Info("Invoking Action: ViewPrintRequested " + numberOfPages.ToString() + " pages.");
                    }
                    catch
                    { }

                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                    info.UseShellExecute = true;
                    info.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Hidden;
                    info.Verb            = "print";
                    info.FileName        = fileName;
                    info.CreateNoWindow  = true;


                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo = info;
                    p.Start();

                    p.WaitForInputIdle();
                    p.CloseMainWindow();

                    /*  if (numberOfPages < Int32.Parse(this.numberOfAvailabelPagesToPrint))
                     * {
                     *    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(numberOfPages));
                     * }
                     * else
                     * {
                     *    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
                     * }*/
                    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(6));

                    if (false == p.CloseMainWindow())
                    {
                        try
                        {
                            p.Kill();
                        }
                        catch { }
                    }
                    else
                    {
                        try
                        {
                            p.Kill();
                        }
                        catch { }
                    }

                    try
                    {
                        //  this.sender.SendAction("Printed " + numberOfPages + " pages.");
                    }
                    catch { }
                    GlobalCounters.numberOfCurrentPrintings += numberOfPages;
                }

                else
                {
                    System.Windows.MessageBox.Show("Unfortunately, you can not print so many pages! Please press OK to continue.");
                }
            }
            catch
            {
            }
            finally
            {
                //response.Close();
            }
        }
Exemple #23
0
        private void Form_Load(object sender, EventArgs e)
        {
            //フォーム非表示
            this.Hide();
            //プロセス生成
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
            psi.FileName    = "C:/Program Files/Mozilla Thunderbird/thunderbird.exe";
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
            //プロセススタート
            System.Diagnostics.Process hProcess = System.Diagnostics.Process.Start(psi);

            //6秒待つ→タイミングがずれた時にうまくいかない→WaitForInputIdleで解決
            //System.Threading.Thread.Sleep(6000);

            //Thunderbirdが起動するまで待つ
            hProcess.WaitForInputIdle();

            //↓↓クラス名が分からない時の処理↓↓

            //アクティブウインドウのウィンドウハンドルを取得
            //IntPtr hwnd = GetForegroundWindow();

            //(もしくはWinspector Spyを利用してクラス名を取得)

            //クラス名の長さを取得
            //int length = GetWindowTextLength(hwnd);

            //クラス名を取得
            //StringBuilder className = new StringBuilder(length);
            //int ret = GetClassName(hwnd, className, length);

            //取得したクラス名をMesssageBoxで表示
            //MessageBox.Show(className.ToString());

            //↑↑クラス名が分からない時の処理↑↑3

            //ウインドウタイトルをプロセス名から取得
            //プロセス一覧からthunderbirdを検知→ウインドウタイトルを変数に格納
            foreach (System.Diagnostics.Process p in
                     System.Diagnostics.Process.GetProcesses())
            {
                if (p.MainWindowTitle.Length != 0)
                {
                    if (p.ProcessName.Contains("thunderbird"))
                    {
                        window_name = p.MainWindowTitle;
                    }
                }
            }

            //事前に調べたクラス名(MozillaWindowClass)とウインドウタイトルからウインドウハンドルを取得
            IntPtr hwnd = FindWindow("MozillaWindowClass", window_name);

            //thunderbirdのウインドウを最小化する
            ShowWindow(hwnd, 6);

            //ウインドウハンドルを閉じる
            hProcess.Close();
            //ウインドウハンドルを破棄する
            hProcess.Dispose();
            //本プログラムを終了させる
            this.Close();
        }
Exemple #24
0
 private void rekenmachineToolStripMenuItem_Click(object sender, EventArgs e)
 {
     System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");
     p.WaitForInputIdle();
 }
Exemple #25
0
        protected void Application_Start()
        {
            Application.Lock();

            string fullname = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

            try
            {
                string path = fullname + System.Configuration.ConfigurationManager.AppSettings.Get("ComosBinFolder");
                if (!System.IO.Directory.Exists(path + "/../Log/"))
                {
                    System.IO.Directory.CreateDirectory(path + "/../Log/");
                }

                LogHandler.logfile = path + "/../Log/" + DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss") + ".ComosBRWeb.log";
                LogHandler.WriteLog("Application_Start!", System.Diagnostics.EventLogEntryType.Error);



                if (TryeRecoverProcess())
                {
                    if (!m_ComosAPIService.IsOpen())
                    {
                        OpenConnString();
                    }

                    Application.UnLock();
                    LogHandler.WriteLog("Comos.IO.Exe was recovered!!");
                    return;
                }
                else
                {
                    LogHandler.WriteLog("Comos.IO.Exe could not be recovered!! Will start new!");
                    CloseComosIOs();
                }

                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.CreateNoWindow  = true;
                startInfo.UseShellExecute = false;
                startInfo.FileName        = path + "\\Comos.IO.exe";

                LogHandler.WriteLog("Comos.IO.Exe.Path::" + startInfo.FileName);

                startInfo.WorkingDirectory = path;
                startInfo.WindowStyle      = System.Diagnostics.ProcessWindowStyle.Hidden;
                m_Process = System.Diagnostics.Process.Start(startInfo);
                m_Process.WaitForInputIdle();

                if (m_Process.HasExited)
                {
                    LogHandler.WriteLog("Comos.Web APIService Exited before it could be opening a database!", System.Diagnostics.EventLogEntryType.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog("Error at:" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                throw;
            }


            //NetNamedPipeBinding binding = new NetNamedPipeBinding();
            NetTcpBinding binding = new NetTcpBinding();

            // Permitir grande quantidade de dados a ser serializado através NamedPipe
            binding.OpenTimeout            = TimeSpan.FromHours(12);
            binding.CloseTimeout           = TimeSpan.FromHours(12);
            binding.ReceiveTimeout         = TimeSpan.FromHours(12);
            binding.SendTimeout            = TimeSpan.FromHours(12);
            binding.MaxBufferPoolSize      = 2147483647;
            binding.MaxBufferSize          = 2147483647;
            binding.MaxReceivedMessageSize = 2147483647;

            //ChannelFactory<IBRServiceContracts.IServiceContract> m_ChannelFactory = new ChannelFactory<IBRServiceContracts.IServiceContract>(binding, new EndpointAddress(@"net.pipe://127.0.0.1/comosio/" + m_Process.Id.ToString()));
            ChannelFactory <IBRServiceContracts.IServiceContract> m_ChannelFactory = new ChannelFactory <IBRServiceContracts.IServiceContract>(binding, new EndpointAddress(@"net.tcp://127.0.0.1:807/comosio/1"));

            // Permitir grande quantidade de objetos a ser serializado através NamedPipe
            m_ChannelFactory.Endpoint.EndpointBehaviors.Add(new IBRServiceContracts.ReaderQuotaExtension());

            m_ComosAPIService = m_ChannelFactory.CreateChannel();
            ((IClientChannel)m_ComosAPIService).OperationTimeout = TimeSpan.FromHours(12);
            ((IClientChannel)m_ComosAPIService).Faulted         += ComosIO_FaultedOnStartup;
            ((IClientChannel)m_ComosAPIService).Opened          += ComosIO_HasBeenOpened;

            // @ToDo: ComosConnectionString, Deve ser um local para banco de dados access em relação ao pasts do site.
            // Isso deve ser alterado assim que o usuário pode colocar o nome de arquivo completo, parente ou uma nome de conexão SQL.

            string connectionstring = System.Configuration.ConfigurationManager.AppSettings.Get("ComosConnectionString");

            if (System.Configuration.ConfigurationManager.AppSettings.Get("ComosConnectionString").ToUpper().Contains(".MDB"))
            {
                connectionstring = fullname + connectionstring;
            }

            bool success = false;

            try
            {
                LogHandler.WriteLog("Comos.Web APIService opening connectionstring : " + connectionstring, System.Diagnostics.EventLogEntryType.Information);
                success = m_ComosAPIService.Open(connectionstring);
                LogHandler.WriteLog("Comos.Web APIService opened connectionstring : " + success.ToString(), System.Diagnostics.EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog("Failed opening comos.io connection at startup");
            }
            if (success)
            {
                LogHandler.WriteLog("Comos.Web Database Opened with success", System.Diagnostics.EventLogEntryType.Information);
                this.Application["ComosAPI"] = m_ComosAPIService;
                ((IClientChannel)m_ComosAPIService).Faulted -= ComosIO_FaultedOnStartup;
                ((IClientChannel)m_ComosAPIService).Faulted += ComosIO_FaultedDuringRequest;
            }
            else
            {
                LogHandler.WriteLog("Comos.Web APIService failed to open : " + connectionstring, System.Diagnostics.EventLogEntryType.Error);
                if (!m_Process.HasExited)
                {
                    m_Process.Kill();
                    m_Process.Dispose();
                }
            }
            //((IClientChannel)m_ComosAPIService).Opened -= ComosAPIService_Opened;
            Application.UnLock();
        }
Exemple #26
0
        private bool PrintPDF(Investment2 newInvestment)
        {
            //Create the PDF for printing
            string FileName = "FIF_" + this.Investor.LastName + this.Investor.FirstName + ".pdf";
            string tempPath = Path.GetTempPath() + FileName;
            try
            {
                //Working code that creates a printable in-memory pdf
                using (PdfReader reader = new PdfReader(Properties.Resources.FIF_CertificateTemplate))
                {
                    using (FileStream fs = new FileStream(tempPath, FileMode.Create))
                    {
                        using (PdfStamper stamper = new PdfStamper(reader, fs))
                        {
                            stampFields(stamper, newInvestment);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(String.Format("Unable to create or print pdf file. \nError Message: {0}", ex.Message));
                File.Delete(tempPath);
                return false;
            }
            try
            {
                string printerPath = "";
                PrintDialog pd = new PrintDialog();
                var result = pd.ShowDialog();
                if (result == DialogResult.OK)
                {
                    printerPath = pd.PrinterSettings.PrinterName;
                }
                else
                {
                    File.Delete(tempPath);
                    return false;
                }

                using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                {

                    process.StartInfo.FileName = tempPath;
                    process.StartInfo.Verb = "printto";
                    process.StartInfo.Arguments = "\"" + printerPath + "\"";

                    process.Start();

                    // I have to use this in case of Adobe Reader to close the window
                    process.WaitForInputIdle();
                    process.Kill();
                    File.Delete(tempPath);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(String.Format("Unable to send PDF to the printer.  \nError Message: ", ex.Message));
                File.Delete(tempPath);
                return false;
            }
            return true;
        }
Exemple #27
0
 private void MenueItemCalculator_Click(object sender, RoutedEventArgs e)
 {
     System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");
     p.WaitForInputIdle();
 }
Exemple #28
0
 private void button1_Click(object sender, EventArgs e)
 {
     System.Diagnostics.Process p = System.Diagnostics.Process.Start("calc.exe");
     p.WaitForInputIdle();
 }
        public static void Launch_ClientAccessSession(
            EhllapiSettings InSettings, string ProfilePath, string SessId,
            LaunchOptions InLaunchOptions)
        {
            int sessCx = 0;

            if (InLaunchOptions == LaunchOptions.WaitForReady)
            {
                sessCx = pcsapi.QueryActiveSessionCount();
            }

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = InSettings.Path_pcsws;

            // enclose the wrkstn profile path in quotes ( in case spaces in the path )
            string profilePath = ProfilePath;

            if (profilePath.IndexOf('"') == -1)
            {
                profilePath = '"' + profilePath + '"';
            }
            proc.StartInfo.Arguments = profilePath;

            //      proc.StartInfo.Arguments =
            //        '"' +@"c:\Program Files\IBM\Client Access\Emulator\private\pc04a.ws" + '"';
            //      proc.StartInfo.Arguments = "'" + InWrkstnProfilePath + "'";
            //      proc.StartInfo.Arguments = @"..\private\pc04a.ws";
            if (SessId.IsNullOrEmpty() == false)
            {
                proc.StartInfo.Arguments = @"/S=" + SessId + " " + proc.StartInfo.Arguments;
            }

            proc.Start();

            proc.WaitForInputIdle(5000);

            // wait until session count increments. that tells us the new session
            // is completely started.
            if (InLaunchOptions == LaunchOptions.WaitForReady)
            {
                int newSessCx = 0;
                while (newSessCx <= sessCx)
                {
                    Thread.Sleep(100);
                    newSessCx = pcsapi.QueryActiveSessionCount();
                }

                // wait until the SessId identified session can be connected to.
                bool isConnected = false;
                int  cummWait    = 0;
                while (isConnected == false)
                {
                    using (DisplaySession sess = new DisplaySession())
                    {
                        try
                        {
                            isConnected = true;
                            sess.Connect(SessId);
                            sess.Wait();
                        }
                        catch (EhllapiExcp)
                        {
                            cummWait += 300;
                            if (cummWait > 10000)
                            {
                                throw new ApplicationException("client access session connection timeout");
                            }
                            isConnected = false;
                            Thread.Sleep(300);
                        }
                    }
                }

                // wait for SystemAvailable.
                int tx = 0;
                while (true)
                {
                    ++tx;
                    if (tx > 1000)
                    {
                        throw new EhllapiExcp("Wait for system available timeout");
                    }
                    using (DisplaySession sess = new DisplaySession())
                    {
                        sess.Connect(SessId);
                        if (sess.SystemAvailable == true)
                        {
                            break;
                        }
                        Thread.Sleep(100);
                    }
                }
            }
        }
Exemple #30
0
 public static void RunApp(string S)
 {
     System.Diagnostics.Process proc = new System.Diagnostics.Process();
     proc.StartInfo.FileName = S;
     proc.Start();
     proc.WaitForInputIdle();
     _Header=proc.MainWindowTitle;
 }
Exemple #31
0
        static void Main()
        {
            //既に起動していたら終了
            if (System.Diagnostics.Process.GetProcessesByName(
                    System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length > 1)
            {
                return;
            }

            string[] cmds;
            cmds = System.Environment.GetCommandLineArgs();

            if (cmds.Length < 2)
            {
                return;
            }
            string cmd = cmds[1].ToLower();
            int    ws  = 0;

            switch (cmd)
            {
            case "normal": ws = 1; break;

            case "min": ws = 2; break;

            case "max":
            default:
                ws = 3; break;
            }


            System.Diagnostics.Process fxP = null;
            IntPtr fxWnd   = (IntPtr)0;
            string fxTitle = "";

            EnumWindows(new EnumWindowsDelegate(delegate(IntPtr hWnd, int lParam)
            {
                StringBuilder sb = new StringBuilder(0x1024);
                if (IsWindowVisible(hWnd) != 0 && GetWindowText(hWnd, sb, sb.Capacity) != 0)
                {
                    string title = sb.ToString();
                    int pid;
                    GetWindowThreadProcessId(hWnd, out pid);
                    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(pid);

                    if (p.ProcessName == "AfterFX")
                    {
                        fxP     = p;
                        fxWnd   = hWnd;
                        fxTitle = title;
                        return(0);
                    }
                }
                return(1);
            }), 0);

            if ((int)fxWnd != 0)
            {
                fxP.WaitForInputIdle();
                ShowWindow(fxWnd, ws);
                SetForegroundWindow(fxWnd);
            }
        }