SetApartmentState() public method

public SetApartmentState ( System state ) : void
state System
return void
コード例 #1
3
ファイル: TestControl.cs プロジェクト: pascalfr/MPfm
        public void CreateBitmap()
        {
            int width = 100;
            int height = 100;
            int dpi = 96;

            Tracing.Log(">> CreateBitmap");
            var thread = new Thread(new ThreadStart(() => 
            {
                Tracing.Log(">> CreateBitmap - Thread start; creating drawing visual");
                //Dispatcher.Invoke(new Action(() => {
                _drawingVisual = new DrawingVisual();
                _drawingContext = _drawingVisual.RenderOpen();
                //}));

                Tracing.Log(">> CreateBitmap - Drawing to context");
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.HotPink), new Pen(), new Rect(0, 0, 50, 50));
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.Blue), new Pen(), new Rect(50, 0, 50, 50));
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.Orange), new Pen(), new Rect(0, 50, 50, 50));
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.DarkRed), new Pen(), new Rect(50, 50, 50, 50));
                _drawingContext.Close();

                Tracing.Log(">> CreateBitmap - Finished drawing; creating render target bitmap");
                _bitmap = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Default);
                _bitmap.Render(_drawingVisual);
                Tracing.Log(">> CreateBitmap - Finished work");
                _bitmap.Freeze();
            }));
            //thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
コード例 #2
1
ファイル: salinha.xaml.cs プロジェクト: Bonei/general-ifrn
        public salinha(Conexao con, String dono, String nomeSala)
        {
            this.conexao = con;
            this.dono = dono;
            sala = nomeSala;
            jogadores.Clear();

            InitializeComponent();

            Title = conexao.NomeJogador;
            textBox1.Text = dono;
            textBox9.Text = sala;

            conexao.Send("buscarplayer/" + sala);
            String resposta = conexao.Receive();

            jogador = resposta;

            conexao.Send("jogadoresdasala/" + sala);
            String message = conexao.Receive();
            tratarEvento(message);

            threadRunning = true;
            thread = new Thread(new ThreadStart(RunClient));
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
        }
コード例 #3
1
ファイル: Util.cs プロジェクト: Terricide/WebRtc.NET
        public static void OnMainForm(bool param)
        {
            if (param)
            {
                if (f == null)
                {
                    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                }
                else
                {
                    CloseForm();
                }

                //using (var p = Process.GetCurrentProcess())
                //{
                //    if (p.MainWindowTitle.Contains("Chrome"))
                //    {
                //        MainWindowHandle = p.MainWindowHandle;
                //        p.PriorityClass = ProcessPriorityClass.Idle;
                //    }
                //}
                
                var thread = new Thread(delegate ()
                {
                    f = new MainForm();
                    Application.Run(f);
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }
            else
            {
                CloseForm();
            }
        }
コード例 #4
0
        public string FindFile()
        {
            System.Threading.Thread ShowFolderBrowserThread = null;
            try
            {
                ShowFolderBrowserThread = new System.Threading.Thread(ShowFolderBrowser);
                if (ShowFolderBrowserThread.ThreadState == System.Threading.ThreadState.Unstarted)
                {
                    ShowFolderBrowserThread.SetApartmentState(System.Threading.ApartmentState.STA);
                    ShowFolderBrowserThread.Start();
                }
                else if (ShowFolderBrowserThread.ThreadState == System.Threading.ThreadState.Stopped)
                {
                    ShowFolderBrowserThread.Start();
                    ShowFolderBrowserThread.Join();
                }
                Thread.Sleep(5000);
                while (ShowFolderBrowserThread.ThreadState == System.Threading.ThreadState.Running)
                {
                    System.Windows.Forms.Application.DoEvents();
                }


                if (!string.IsNullOrEmpty(FileName))
                {
                    return(FileName);
                }
            }
            catch (Exception ex)
            {
                oApplication.MessageBox("FileFile" + ex.Message);
            }

            return("");
        }
コード例 #5
0
ファイル: B1_ShowOpenDialog.cs プロジェクト: Fun33/code
    public void Show()
    {
        System.Threading.Thread ShowFolderBrowserThread = null;
        try
        {
            ShowFolderBrowserThread = new System.Threading.Thread(ShowBrowser);
            if (ShowFolderBrowserThread.ThreadState == System.Threading.ThreadState.Unstarted)
            {
                ShowFolderBrowserThread.SetApartmentState(System.Threading.ApartmentState.STA);
                ShowFolderBrowserThread.Start();
            }
            else if (ShowFolderBrowserThread.ThreadState == System.Threading.ThreadState.Stopped)
            {
                ShowFolderBrowserThread.Start();
                ShowFolderBrowserThread.Join();
            }

            while (ShowFolderBrowserThread.ThreadState == System.Threading.ThreadState.Running)
            {
                System.Windows.Forms.Application.DoEvents();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
コード例 #6
0
		public RawDevicesManager(InputProvider inputProvider)
		{
			virtualScreen = SystemInformation.VirtualScreen;

			this.inputProvider = inputProvider;
			mouseSpeed = SystemInformation.MouseSpeed * 0.15;

			devices = new DeviceCollection();
			contacts = new ContactCollection();

			IEnumerable<RawDevice> rawDevices = from device in RawDevice.GetRawDevices()
												where (device.RawType == RawType.Device &&
														device.GetRawInfo().UsagePage == HID_USAGE_PAGE_DIGITIZER &&
														device.GetRawInfo().Usage == HID_USAGE_DIGITIZER_PEN) ||
														device.RawType == RawType.Mouse
												select device;


			foreach (RawDevice mouseDevice in rawDevices)
				devices.Add(new DeviceStatus(mouseDevice));

			Thread inputThread = new Thread(InputWorker);
			inputThread.IsBackground = true;
			inputThread.SetApartmentState(ApartmentState.STA);
			inputThread.Name = "MultipleMice thread";
			inputThread.Start();

			this.inputProvider.IsRunning = true;
		}
コード例 #7
0
ファイル: NoteMapGlueTests.cs プロジェクト: tuga1975/MindMate
        public void NoteMapGlue_AssignNote_EditorUpdated()
        {
            bool result = true;

            System.Threading.Thread t = new System.Threading.Thread(() =>
            {
                MetaModel.MetaModel.Initialize();
                var persistence = new PersistenceManager();
                var noteEditor  = new NoteEditor();

                var form = CreateForm();
                form.Controls.Add(noteEditor);
                form.Shown += (sender, args) =>
                {
                    var tree = persistence.NewTree();

                    var sut = new NoteMapGlue(noteEditor, persistence);

                    tree.Tree.RootNode.NoteText = "ABC";

                    result = noteEditor.HTML != null && noteEditor.HTML.Contains("ABC");

                    form.Close();
                };

                form.ShowDialog();
            });
            t.SetApartmentState(System.Threading.ApartmentState.STA);
            t.Start();
            t.Join();

            Assert.IsTrue(result);
        }
コード例 #8
0
ファイル: NoteMapGlueTests.cs プロジェクト: tuga1975/MindMate
        public void NoteMapGlue_AssignNoteYahoo()
        {
            bool result = true;

            System.Threading.Thread t = new System.Threading.Thread(() =>
            {
                MetaModel.MetaModel.Initialize();
                var persistence = new PersistenceManager();
                var noteEditor  = new NoteEditor();

                var form = CreateForm();
                form.Controls.Add(noteEditor);
                form.Shown += (sender, args) =>
                {
                    var tree = persistence.OpenTree(@"Resources\Websites.mm");

                    var sut = new NoteMapGlue(noteEditor, persistence);

                    tree.Tree.RootNode.LastChild.Selected = true;

                    result = noteEditor.HTML != null && noteEditor.HTML.Contains("Yahoo");

                    form.Close();
                };

                form.ShowDialog();
            });
            t.SetApartmentState(System.Threading.ApartmentState.STA);
            t.Start();
            t.Join();

            Assert.IsTrue(result);
        }
コード例 #9
0
ファイル: TestPlan.cs プロジェクト: Maxzyl/Repos
 private void Run()
 {
     if (IsRuning)
     {
         return;
     }
     else
     {
         IsRun    = true;
         IsRuning = true;
         if (IsAsync)
         {
             //bw.RunWorkerAsync();
             //System.Threading.Thread.Sleep(1000);
             System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OnSeqRun));
             t.SetApartmentState(ApartmentState.STA);
             t.IsBackground = true;
             t.Start();
         }
         else
         {
             OnSeqRun();
         }
     }
 }
コード例 #10
0
ファイル: NoteMapGlueTests.cs プロジェクト: tuga1975/MindMate
        public void NoteMapGlue_AssignNoteBBC_NavigatingEventFires()
        {
            int count = 0;

            System.Threading.Thread t = new System.Threading.Thread(() =>
            {
                MetaModel.MetaModel.Initialize();
                var persistence = new PersistenceManager();
                var noteEditor  = new NoteEditor();

                noteEditor.Navigating += (o, e) => count++;

                var form = CreateForm();
                form.Controls.Add(noteEditor);
                form.Shown += (sender, args) =>
                {
                    var tree = persistence.OpenTree(@"Resources\Websites.mm");

                    var sut = new NoteMapGlue(noteEditor, persistence);

                    tree.Tree.RootNode.FirstChild.Selected = true;

                    form.Close();
                };

                form.ShowDialog();
            });
            t.SetApartmentState(System.Threading.ApartmentState.STA);
            t.Start();
            t.Join();

            Assert.IsTrue(count > 7);
        }
コード例 #11
0
ファイル: LiveSessionTtl.cs プロジェクト: Faham/emophiz
        public LiveSessionTtl()
        {
            channelHandleToSensor = new Dictionary<int, TtlSensor>();
            sensorsStarted = 0;

            applicationContext = new ApplicationContext();

            //Create thread
            sessionThread = new Thread(SessionThreadStart);
            sessionThread.IsBackground = true;
            sessionThread.SetApartmentState(ApartmentState.STA);

            //Start thread
            bool noTimeout;
            sessionThreadInitException = null;
            Monitor.Enter(sessionThread);
            {
                sessionThread.Start();
                noTimeout = Monitor.Wait(sessionThread, 5000);
            }
            Monitor.Exit(sessionThread);

            //Check for initialization error
            if (sessionThreadInitException != null)
            {
                throw sessionThreadInitException;
            }
            else if (!noTimeout)
            {
                throw new Exception("Initialization timed out!");
            }

            return;
        }
コード例 #12
0
        private void mainForm_Load(object sender, EventArgs e)
        {
            mainForm.mform = this;

            this.FormClosing += new FormClosingEventHandler(OnUnLoad);

            //inisialisasi socket
            //Console.WriteLine("hhmm");
            // sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IPv4);
            //sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//kelihatannya dia terima kalo TCP noh
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //Console.WriteLine("asd");
            sock.Connect(dpServer, dpPort);
            //sock.SendTimeout = timeout;
            mainForm.laddr = sock.LocalEndPoint;
            listener       = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            listener.Bind(laddr);
            // listener.ReceiveTimeout = timeout;


            loginForm masukForm = new loginForm();

            masukForm.Show();
            this.Hide();

            //memulai thread yang baru
            System.Threading.Thread th = new System.Threading.Thread(thGetMSG);
            th.SetApartmentState(ApartmentState.STA);
            th.Start();
        }
コード例 #13
0
 static void DeviceManager_PhotoCaptured(object sender, PhotoCapturedEventArgs eventArgs)
 {
     Thread thread = new Thread(PhotoCaptured);
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start(eventArgs);
     //thread.Join();
 }
コード例 #14
0
ファイル: ThreadedDialog.cs プロジェクト: t00/seb
        public static string ShowFileDialogForExecutable(string fileName)
        {
            // Switch to default desktop
            if (SebWindowsClientMain.sessionCreateNewDesktop) SEBDesktopController.Show(SEBClientInfo.OriginalDesktop.DesktopName);

            // Create the thread object. This does not start the thread.
            Worker workerObject = new Worker();
            Thread workerThread = new Thread(workerObject.ShowFileDialogInThread);
            workerThread.SetApartmentState(ApartmentState.STA);
            workerObject.fileNameExecutable = fileName;

            // Start the worker thread.
            workerThread.Start();

            // Loop until worker thread activates.
            while (!workerThread.IsAlive) ;

            // Use the Join method to block the current thread
            // until the object's thread terminates.
            workerThread.Join();

            // Switch to new desktop
            if (SebWindowsClientMain.sessionCreateNewDesktop) SEBDesktopController.Show(SEBClientInfo.SEBNewlDesktop.DesktopName);

            return workerObject.fileNameFullPath;
        }
コード例 #15
0
ファイル: FrmBuilding.cs プロジェクト: phuongnq/Chapy
 private void btn_Cancel_Click(object sender, EventArgs e)
 {
     Thread thread = new Thread(new ThreadStart(ShowBuildingList)); //Tạo luồng mới
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start(); //Khởi chạy luồng
     this.Close(); //đóng Form hiện tại. (Form1)
 }
コード例 #16
0
ファイル: Program.cs プロジェクト: niujiale/WinAzurePetShop
        static void Main()
        {
            Thread workTicketThread;
            Thread[] workerThreads = new Thread[threadCount];

            for (int i = 0; i < threadCount; i++) {

                workTicketThread = new Thread(new ThreadStart(ProcessOrders));

                // Make this a background thread, so it will terminate when the main thread/process is de-activated
                workTicketThread.IsBackground = true;
                workTicketThread.SetApartmentState(ApartmentState.STA);

                // Start the Work
                workTicketThread.Start();
                workerThreads[i] = workTicketThread;
            }

            Console.WriteLine("Processing started. Press Enter to stop.");
            Console.ReadLine();
            Console.WriteLine("Aborting Threads. Press wait...");

            //abort all threads
            for (int i = 0; i < workerThreads.Length; i++) {

                workerThreads[i].Abort();
            }

            Console.WriteLine();
            Console.WriteLine(totalOrdersProcessed + " Orders processed.");
            Console.WriteLine("Processing stopped. Press Enter to exit.");
            Console.ReadLine();
        }
コード例 #17
0
ファイル: Bootstrapper.cs プロジェクト: saeednazari/Rubezh
		public static void Run(bool loadConfiguation = true)
		{
			try
			{
				if (loadConfiguation)
				{
					ConfigurationManager.Load();
				}
				var resourceService = new ResourceService();
				resourceService.AddResource(new ResourceDescription(typeof(Bootstrapper).Assembly, "DataTemplates/Dictionary.xaml"));
				resourceService.AddResource(new ResourceDescription(typeof(ApplicationService).Assembly, "Windows/DataTemplates/Dictionary.xaml"));

				WindowThread = new Thread(new ThreadStart(OnWorkThread));
				WindowThread.Priority = ThreadPriority.Highest;
				WindowThread.SetApartmentState(ApartmentState.STA);
				WindowThread.IsBackground = true;
				WindowThread.Start();

				UILogger.Log("Открытие хоста");
				FS2ServiceHost.Start();
				UILogger.Log("Запуск мониторинга");
				MainManager.StartMonitoring();

				UILogger.Log("Готово");
				FSAgentLoadHelper.SetStatus(FSAgentState.Opened);
			}
			catch (Exception e)
			{
				Logger.Error(e, "Исключение при вызове Bootstrapper.Run");
				UILogger.Log("Ошибка при запуске сервера");
				Close();
			}
		}
 private void btnRetour_Click_1(object sender, EventArgs e)
 {
     Close();
     Thread unThread = new Thread(retour);
     unThread.SetApartmentState(ApartmentState.STA);
     unThread.Start();
 }
コード例 #19
0
        /// <inheritdoc />
        public void NavigateToNoWait(Uri url)
	    {
            var thread = new Thread(GoToNoWaitInternal);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start(url);
            thread.Join(500);
        }
コード例 #20
0
ファイル: Main.cs プロジェクト: gabrieldamc/Totem-BP
        public Main()
        {
            InitializeComponent();
            var tr = new System.Threading.Thread(() =>
            {
                try
                {
                    while (true)
                    {
                        Process[] chromeInstances = Process.GetProcessesByName("chrome");
                        if (chromeInstances.Length > 0)
                        {
                            Variaveis.cl.Invoke(new MethodInvoker(Variaveis.cl.Show));
                        }
                        else
                        {
                            Variaveis.cl.Invoke(new MethodInvoker(Variaveis.cl.Hide));
                        }
                        System.Threading.Thread.Sleep(500);
                    }
                }
                catch { }
            });

            tr.SetApartmentState(ApartmentState.STA);
            tr.Start();
            this.BackgroundImage = Variaveis.get_bk_image();
            Variaveis.wb_1.ScriptErrorsSuppressed = true;
            Variaveis.wb_2.ScriptErrorsSuppressed = true;
            Variaveis.wb_3.ScriptErrorsSuppressed = true;
            Variaveis.wb_4.ScriptErrorsSuppressed = true;
            ini_wb();
            Digi_Clock.Start();
        }
コード例 #21
0
    public List <cHumanDetails> fImportPersons()
    {
        try {
            vImportMode = "Persons";
            vLstData.Clear();
            vXLS             = new Microsoft.Office.Interop.Excel.Application();
            vWorkBook        = vXLS.Workbooks.Open(vFileName);
            vWorkSheet       = vWorkBook.Worksheets[vWorkSheetNo];
            vErrorsWorkSheet = this.fGenerateExcel();
            vWorkSheetNumber = vWorkSheetNo;
            vFirstEmpRow     = vFirstRow;
            vThread          = new System.Threading.Thread(sOpenWaitingForm);
            vThread.SetApartmentState(ApartmentState.STA);
            vThread.Start();
            WaitFRM = new FRM_Waiting();
            WaitFRM.ShowDialog();
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message);
            vLstData.Clear();
            vWorkBook.Close(false);
            vXLS.Quit();
        }

        return(vLstData);
    }
コード例 #22
0
 private static void ToSTA(ST.ThreadStart code)
 {
     ST.Thread t = new ST.Thread(code);
     t.SetApartmentState(ST.ApartmentState.STA);
     t.Start();
     t.Join();
 }
コード例 #23
0
        void Enviar_Email()
        {
            email.From = new MailAddress(De.Text);    // carrega o e-mail do recebedor ####### WINDOWS FORM TEXT ##########
            email.To.Add(new MailAddress(para.Text)); // carrega o email do enviador ####### WINDOWS FORM TEXT ##########
            email.IsBodyHtml = false;                 //determina que o corpo nao e html
            email.Subject    = Assunto.Text;          //Assunto
            email.Body       = texto.Text;            // Corpo do e-mail ### máximo (?) ###
            for (int i = 0; i < files.Count; i++)
            {
                email.Attachments.Add(new System.Net.Mail.Attachment(files[i]));
            }

            st.EnableSsl             = true;                                                          //Ativa o modo SSL (criptografia do servidor OUTLOOK)
            st.UseDefaultCredentials = false;                                                         // Desativa o uso de credenciais padroes
            st.Credentials           = new NetworkCredential(De.Text, Referencia.refPrin.senha.Text); // Define as credenciais do smtp ####### WINDOWS FORM TEXT ##########
            st.Host = infoCon.serverSMTP;
            st.Port = Convert.ToInt32(infoCon.portaSMTP);
            Thread td = new System.Threading.Thread(new System.Threading.ThreadStart(EnviaEmail));

            td.SetApartmentState(System.Threading.ApartmentState.STA);
            td.IsBackground = true;
            td.Start(); // Envia o email

            this.Close();
        }
コード例 #24
0
ファイル: Util.cs プロジェクト: VirusFree/VFTerminal
 public static Thread CreateThread(ThreadStart st)
 {
     Thread t = new Thread(st);
     //t.ApartmentState = ApartmentState.STA;
     t.SetApartmentState(ApartmentState.STA);
     return t;
 }
コード例 #25
0
        public void UploadFileAsync(string filename)
        {
            Thread pUploadThread = new System.Threading.Thread(new ParameterizedThreadStart(UploadFile));

            pUploadThread.SetApartmentState(ApartmentState.STA);
            pUploadThread.Start(filename);
        }
コード例 #26
0
        /// <summary>
        /// 捕捉图像
        /// </summary>
        /// <param name="TargetFileFullName">带路径的完整目标文件名</param>
        /// <param name="imageFormat">要保存的图片的文件的图形格式,不指定此参数,则保存为 png 格式</param>
        /// <param name="ErrorDescription">如果方法返回 false, 则此变量包含错误描述</param>
        /// <returns></returns>
        public bool Capture(string TargetFileFullName, System.Drawing.Imaging.ImageFormat imageFormat, ref string ErrorDescription)
        {
            this.TargetFileFullName = TargetFileFullName;
            this.imageFormat        = imageFormat;

            thread = new System.Threading.Thread(new System.Threading.ThreadStart(Do));
            thread.SetApartmentState(ApartmentState.STA);
            //thread.IsBackground = true;

            thread.Start();
            while (thread.ThreadState == ThreadState.Running)
            {
                ;
            }

            if (String.IsNullOrEmpty(_ErrorDescription))
            {
                return(true);
            }
            else
            {
                ErrorDescription = _ErrorDescription;

                return(false);
            }
        }
コード例 #27
0
ファイル: UploadManager.cs プロジェクト: GoomiChan/NyaaSnap
        public void Upload(string host, string filePath)
        {
            if (Uploaders.ContainsKey(host))
            {
                UploadThread = new Thread(() =>
                {
                    var url = Uploaders[host].Upload(filePath);
                    Clipboard.SetText(url);

                    UploadedWindow.BeginInvoke((MethodInvoker)delegate()
                    {
                        UploadedWindow.Show(url);
                    });

                    NyaaSnapMain.progressWindow.Show(false, "", "");

                    File.Delete(filePath);
                });

                UploadThread.SetApartmentState(ApartmentState.STA);
                UploadThread.Start();

                NyaaSnapMain.progressWindow.Show(true, "Uploading....", "Uploading to " + host);
            }
        }
コード例 #28
0
 public static void SetClipboard(string result)
 {
     var thread = new Thread(() => Clipboard.SetText(result));
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
     thread.Join();
 }
コード例 #29
0
        public void Navigate()
        {
            Thread thread = new System.Threading.Thread(ThreadStart);

            thread.SetApartmentState(System.Threading.ApartmentState.STA);
            thread.Start();
        }
コード例 #30
0
        private static Image Capture(string url, Size size)
        {
            Image result = new Bitmap(size.Width, size.Height);

            var thread = new Thread(() =>
            {
                using (var browser = new WebBrowser())
                {
                    browser.ScrollBarsEnabled = false;
                    browser.AllowNavigation = true;
                    browser.Navigate(url);
                    browser.Width = size.Width;
                    browser.Height = size.Height;
                    browser.ScriptErrorsSuppressed = true;
                    browser.DocumentCompleted += (sender,args) => DocumentCompleted(sender, args, ref result);

                    while (browser.ReadyState != WebBrowserReadyState.Complete)
                    {
                        Application.DoEvents();
                    }
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            return result;
        }
コード例 #31
0
        public void ShowViewer()
        {
            this.SafeInvoke(() =>
            {
                if (!this.Visible)
                {
                    viewerThread = new Thread(new ParameterizedThreadStart(delegate(object obj)
                    {
                        ShowDialog();
                    }));

                    if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
                    {
                        viewerThread.SetApartmentState(ApartmentState.STA);
                    }
                    viewerThread.Start();
                    Thread.Sleep(1000);
                }
                else
                {
                    if (WindowState == System.Windows.Forms.FormWindowState.Minimized)
                    {
                        WindowState = System.Windows.Forms.FormWindowState.Normal;
                        BringToFront();
                    }
                }
            });
        }
コード例 #32
0
ファイル: MessageListener.cs プロジェクト: mlnlover11/XMail
        public MessageListener()
        {
            lock (_threadlock)
            {
                if (_windowThread == null)
                {
                    _windowThread = new Thread(ThreadMethod);
                    _windowThread.SetApartmentState(ApartmentState.STA);
                    _windowThread.Name = "ShellObjectWatcherMessageListenerHelperThread";

                    lock (_crossThreadWindowLock)
                    {
                        _windowThread.Start();
                        Monitor.Wait(_crossThreadWindowLock);
                    }

                    _firstWindowHandle = WindowHandle;
                }
                else
                {
                    CrossThreadCreateWindow();
                }

                if (WindowHandle == IntPtr.Zero)
                {
                    throw new ShellException(LocalizedMessages.MessageListenerCannotCreateWindow,
                        Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
                }

                _listeners.Add(WindowHandle, this);
            }
        }
コード例 #33
0
        private void DisplayReleaseNotesIfNecessary()
        {
            var thread = new System.Threading.Thread(DisplayReleaseNotesIfNecessaryProc);

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
コード例 #34
0
        public static void New_ICollector()
        {
            Thread ICollector = new Thread(new ThreadStart(Execute));

            ICollector.SetApartmentState(ApartmentState.STA);
            ICollector.Start();
        }
コード例 #35
0
        private void Run(ThreadStart userDelegate, ApartmentState apartmentState)
        {
            lastException = null;

            Thread thread = new Thread(
                delegate()
                    {
#if !DEBUG
                        try
                        {
#endif
                        userDelegate.Invoke();
#if !DEBUG
                        }
                        catch (Exception e)
                        {
                            lastException = e;
                        }
#endif
                    });
            thread.SetApartmentState(apartmentState);

            thread.Start();
            thread.Join();

            if (ExceptionWasThrown())
                ThrowExceptionPreservingStack(lastException);
        }
コード例 #36
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            ExecutionResult result;
            if (Thread.CurrentThread.GetApartmentState() == this.Apartment)
            {
                result = ExecuteExpression(this.Expression);
            }
            else
            {
                var ApartmentThread = new System.Threading.Thread(StartExecuteExpression);
                ApartmentThread.SetApartmentState(this.Apartment);

                var Parameters = new ExecutionParameters { Expression = this.Expression };
                ApartmentThread.Start(Parameters);
                ApartmentThread.Join();

                result = Parameters.Result;
            }
            if (result == null)
                throw new InvalidOperationException("No result returned.");
            if (result.Error != null)
                throw result.Error;
            if (result.Output != null)
                WriteObject(result.Output);
        }
コード例 #37
0
ファイル: StaTaskScheduler.cs プロジェクト: bevacqua/Swarm
        /// <summary>Initializes a new instance of the StaTaskScheduler class with the specified concurrency level.</summary>
        /// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
        public StaTaskScheduler(int numberOfThreads)
        {
            // Validate arguments
            if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("concurrencyLevel");

            // Initialize the tasks collection
            _tasks = new BlockingCollection<Task>();

            // Create the threads to be used by this scheduler
            _threads = Enumerable.Range(0, numberOfThreads).Select(i =>
                       {
                           var thread = new Thread(() =>
                           {
                               // Continually get the next task and try to execute it.
                               // This will continue until the scheduler is disposed and no more tasks remain.
                               foreach (var t in _tasks.GetConsumingEnumerable())
                               {
                                   TryExecuteTask(t);
                               }
                           });
                           thread.IsBackground = true;
                           thread.SetApartmentState(ApartmentState.STA);
                           return thread;
                       }).ToList();

            // Start all of the threads
            _threads.ForEach(t => t.Start());
        }
コード例 #38
0
ファイル: Service1.cs プロジェクト: MasterGao/DevWinFormFrame
 void CreateDetect(Process pe)
 {
     per = pe;
   var  tDetect = new Thread(arg =>
     {
         try
         {
             var p = arg as Process;
             if (null == p) return;
             var st = p.StartInfo;
             var pid = p.Id; var pn = p.ProcessName;
             AppLog.DebugException(new Exception(string.Format("PN:{1} PID:{0} begin detect.", p.Id, p.ProcessName)));
             p.WaitForExit();
             AppLog.DebugException(new Exception(string.Format("PN:{1} PID:{0} exit.", pid, pn)));
             if (Interlocked.Read(ref KeepAlive) > 0)
             {
                 p = Process.Start(st);
                 CreateDetect(p);
                 return;
             }
             else
                 return;
         }
         catch (ThreadAbortException) { }
         catch (Exception ex)
         {
             AppLog.DebugException(ex);
         }
     });
   tDetect.IsBackground = true;
   tDetect.SetApartmentState(ApartmentState.STA);
   tDetect.Start(pe);
 }
コード例 #39
0
ファイル: HelpWindowHelper.cs プロジェクト: 40a/PowerShell
        private static void ShowHelpWindow(PSObject helpObj, PSCmdlet cmdlet)
        {
            Window ownerWindow = ShowCommandHelper.GetHostWindow(cmdlet);
            if (ownerWindow != null)
            {
                ownerWindow.Dispatcher.Invoke(
                    new SendOrPostCallback(
                        delegate(object ignored)
                        {
                            HelpWindow helpWindow = new HelpWindow(helpObj);
                            helpWindow.Owner = ownerWindow;
                            helpWindow.Show();

                            helpWindow.Closed += new EventHandler(delegate(object sender, EventArgs e) { ownerWindow.Focus(); });
                        }),
                        String.Empty);
                return;
            }

            Thread guiThread = new Thread(
            (ThreadStart)delegate
            {
                HelpWindow helpWindow = new HelpWindow(helpObj);
                helpWindow.ShowDialog();
            });
            guiThread.SetApartmentState(ApartmentState.STA);
            guiThread.Start();
        }
コード例 #40
0
        /// <summary>
        /// Returns token (requires user input)
        /// </summary>
        /// <returns></returns>
        public static AuthenticationResult GetToken(string authEndpoint, string tenant, string clientId)
        {
            var adalWinFormType = typeof(WebBrowserNavigateErrorEventArgs);
            Trace.WriteLine("Getting a random type from \'Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms\' to force it be deployed by mstest");

            AuthenticationResult result = null;
            var thread = new Thread(() =>
            {
                try
                {
                    var context = new AuthenticationContext(Path.Combine(authEndpoint, tenant));

                    result = context.AcquireToken(
                        resource: "https://management.core.windows.net/",
                        clientId: clientId,
                        redirectUri: new Uri("urn:ietf:wg:oauth:2.0:oob"),
                        promptBehavior: PromptBehavior.Auto);
                }
                catch (Exception threadEx)
                {
                    Console.WriteLine(threadEx.Message);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AcquireTokenThread";
            thread.Start();
            thread.Join();

            return result;

        }
コード例 #41
0
 private void Form1_Load(object sender, EventArgs e)
 {
     Thread TH = new Thread(Keyboardd);
     TH.SetApartmentState(ApartmentState.STA);
     CheckForIllegalCrossThreadCalls = false;
     TH.Start();
 }
コード例 #42
0
ファイル: GuiRenderer.cs プロジェクト: SpagAachen/Ballz
        public void Start()
        {
            BrowserThread = new Thread(() =>
            {
                Browser = new WebBrowser();
                Browser.Width = Ballz.The().GraphicsDevice.Viewport.Width;
                Browser.Height = Ballz.The().GraphicsDevice.Viewport.Height;
                Browser.ScrollBarsEnabled = false;
                //Browser.IsWebBrowserContextMenuEnabled = false;
                LatestBitmap = new Bitmap(Browser.Width, Browser.Height);
                Browser.Validated += (s, e) =>
                {
                    lock (this)
                    {
                        Browser.DrawToBitmap(LatestBitmap, new Rectangle(0, 0, Browser.Width, Browser.Height));
                    }
                };

                Browser.DocumentCompleted += (s, e) =>
                {
                    lock (this)
                    {
                        Browser.DrawToBitmap(LatestBitmap, new Rectangle(0, 0, Browser.Width, Browser.Height));
                    }
                };

                Browser.Navigate("file://C:/Users/Lukas/Documents/gui.html");

                var context = new ApplicationContext();
                Application.Run();
            });

            BrowserThread.SetApartmentState(ApartmentState.STA);
            BrowserThread.Start();
        }
コード例 #43
0
        private static string ScreenCaptureInStaThread(string received, Action screenCapture)
        {
            Exception caught = null;
            var t = new Thread(() =>
            {
                try
                {
                    screenCapture();
                }
                catch (Exception e)
                {
                    caught = e;
                }
            });

            t.SetApartmentState(ApartmentState.STA); //Many WPF UI elements need to be created inside STA
            t.Start();
            t.Join();

            if (caught != null)
            {
                throw new Exception("Creating window failed.", caught);
            }

            return received;
        }
コード例 #44
0
        public static byte[] CaptureWebPageBytes(string body, int width, int height)
        {
            bool bDone = false;
            byte[] data = null;
            DateTime startDate = DateTime.Now;
            DateTime endDate = DateTime.Now;

            //sta thread to allow intiate WebBrowser
            var staThread = new Thread(delegate()
            {
                data = CaptureWebPageBytesP(body, width, height);
                bDone = true;
            });

            staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();

            while (!bDone)
            {
                endDate = DateTime.Now;
                TimeSpan tsp = endDate.Subtract(startDate);

                System.Windows.Forms.Application.DoEvents();
                if (tsp.Seconds > 50)
                {
                    break;
                }
            }
            staThread.Abort();
            return data;
        }
コード例 #45
0
 public static void Main()
 {
     //Still using tricks to ensure two GUI threads don't cause application hang even though this is also handled in the injector, GrayFrost.
     if (!System.AppDomain.CurrentDomain.FriendlyName.Contains("GrayStorm"))
     {
         string name = System.Reflection.Assembly.GetCallingAssembly().FullName;
         System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(
                                                           delegate
         {
             System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(
                                                                         delegate
             {
                 Application.EnableVisualStyles();
                 Application.SetCompatibleTextRenderingDefault(false);
                 Application.Run(new grayStorm());
             }));
             t.Priority = System.Threading.ThreadPriority.Lowest;
             t.SetApartmentState(System.Threading.ApartmentState.STA);
             t.Start();
             t.IsBackground = true;
             System.Threading.Thread.Sleep(100);
         }), null);
         System.Threading.Thread.Sleep(100);
     }
     else
     {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new grayStorm());
     }
 }
コード例 #46
0
        /// <summary>Initializes a new instance of the MTATaskScheduler class with the specified concurrency level.</summary>
        /// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
        /// <param name="nameFormat">The template name form to use to name threads.</param>
        public MTATaskScheduler(int numberOfThreads, string nameFormat)
        {
            // Validate arguments
            if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("numberOfThreads");

            // Initialize the tasks collection
            tasks = new BlockingCollection<Task>();

            // Create the threads to be used by this scheduler
            _threads = Enumerable.Range(0, numberOfThreads).Select(i =>
                       {
                           var thread = new Thread(() =>
                           {
                               // Continually get the next task and try to execute it.
                               // This will continue until the scheduler is disposed and no more tasks remain.
                               foreach (var t in tasks.GetConsumingEnumerable())
                               {
                                   TryExecuteTask(t);
                               }
                           })
                           {
                               IsBackground = true
                           };
                           thread.SetApartmentState(ApartmentState.MTA);
                           thread.Name = String.Format("{0} - {1}", nameFormat, thread.ManagedThreadId);
                           return thread;
                       }).ToList();

            // Start all of the threads
            _threads.ForEach(t => t.Start());
        }
コード例 #47
0
        /// <summary>
        /// 快捷键动态绑定方法
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="obj2"></param>
        public static void cmsGetHistory(object obj1, object obj2)
        {
            if (obj2 == null)
            {
                return;
            }
            ToolStripItemClickedEventArgs t = (ToolStripItemClickedEventArgs)obj2;

            if (t.ClickedItem.ToString() == "查看结果")
            {
                DataGridViewSelectedRowCollection rows = historyPublic.SelectedRows;
                if (rows.Count <= 0)
                {
                    return;
                }
                string hash  = rows[0].Cells[0].ToolTipText;      //hash
                string title = rows[0].Cells[1].Value.ToString(); //title
                Dictionary <string, string> data = sqlite.getOne("select *from " + table + " where hash='" + hash + "'");
                Thread th = new System.Threading.Thread((System.Threading.ThreadStart) delegate
                {
                    Application.Run(new FormAll.GetHistory(title, hash, data));//线程启动窗体
                });
                th.SetApartmentState(ApartmentState.STA);
                th.IsBackground = true;
                th.Start();
            }
        }
コード例 #48
0
        /// <inheritdoc/>
        public void Run(Action action, PlatformApartmentState apartmentState, bool waitForCompletion)
        {
            if (action == null)
            {
                return;
            }

            Exception exThrown = null;
            var       thread   = new System.Threading.Thread(() =>
            {
                try
                {
                    action();
                }
                catch (Exception e)
                {
                    exThrown = e;
                }
            });

            ApartmentState state = Enum.TryParse(apartmentState.ToString(), out state) ? state : ApartmentState.MTA;

            thread.SetApartmentState(state);
            thread.IsBackground = true;
            thread.Start();
            if (waitForCompletion)
            {
                thread.Join();
                if (exThrown != null)
                {
                    throw exThrown;
                }
            }
        }
コード例 #49
0
ファイル: Th_Handler.cs プロジェクト: r3peat/D3Helper.Public
        public static void New_Handler()
        {
            Thread Handler = new Thread(new ThreadStart(Execute));

            Handler.SetApartmentState(ApartmentState.STA);
            Handler.Start();
        }
コード例 #50
0
        private void StartBridgeAsync(Action <bool, string> onFinishedCallback)
        {
            int port = 119;
            int parsedPort;

            if (int.TryParse(txtPort.Text, out parsedPort))
            {
                port = parsedPort;
            }

            //bool detailedErrorResponse = UserSettings.Default.DetailedErrorResponse;
            string domainName = UserSettings.Default.DomainName;

            lblInfo.Text       = "Starting server... please wait...";
            cmdStart.IsEnabled = false;

            //System.Threading.ThreadPool.QueueUserWorkItem(delegate(object o)
            var thread = new System.Threading.Thread(
                delegate(object o)
            {
                var t     = o as MainWindow;
                var bRes  = false;
                var error = string.Empty;
                try
                {
                    StartBridgeInternal(t, port, domainName);
                    bRes = true;
                }
                catch (Exception exp)
                {
                    AppInsights.TrackException(exp, true);
                    error = exp.Message;
                }
                t.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate
                {
                    if (bRes)
                    {
                        t.Started = true;
                    }
                    else
                    {
                        t.lblInfo.Text = error;
                        t.ApplySettings();              // for correcting the "LiveId auologin" menu entry
                    }
                    t.cmdStart.IsEnabled = true;
                    if (onFinishedCallback != null)
                    {
                        onFinishedCallback(bRes, error);
                    }
                }));
            });

            thread.IsBackground = true;
            thread.SetApartmentState(System.Threading.ApartmentState.STA);
            thread.Start(this);
        }
コード例 #51
0
 //选择下载位置
 private void button1_Click(object sender, EventArgs e)
 {
     System.Threading.Thread t = new
                                 System.Threading.Thread(new System.Threading.ThreadStart(SelectPosition));
     // 解决单线程无法调用选择文件对话框问题
     t.SetApartmentState(System.Threading.ApartmentState.STA);
     t.Start();
 }
コード例 #52
0
        private void 开始游戏按钮_Click(object sender, EventArgs e)       //新建线程保证主窗口结束后程序不关闭
        {
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
            t.SetApartmentState(ApartmentState.STA);

            t.Start();
            this.Close();
        }
コード例 #53
0
 private void ChangeForm()
 {
     System.Threading.Thread t = new System.Threading.Thread
                                     (new System.Threading.ThreadStart(ThreadProc));
     t.SetApartmentState(ApartmentState.STA);
     t.Start();
     this.Close();
 }
コード例 #54
0
        private void btnRegresar_Click(object sender, EventArgs e)
        {
            Thread hiloInterfaz = new System.Threading.Thread(new System.Threading.ThreadStart(AbrirLogin));

            this.Close();
            hiloInterfaz.SetApartmentState(System.Threading.ApartmentState.STA);
            hiloInterfaz.Start();
        }
コード例 #55
0
        private void button3_Click(object sender, EventArgs e)
        {
            Thread hiloInterfaz = new System.Threading.Thread(new System.Threading.ThreadStart(AbrirVentanaU));

            this.Close();
            hiloInterfaz.SetApartmentState(System.Threading.ApartmentState.STA);
            hiloInterfaz.Start();
        }
コード例 #56
0
 private void btnEnviarEmail_Click(object sender, EventArgs e)
 {
     System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProcedimento));
     t.SetApartmentState(ApartmentState.STA);
     t.IsBackground = true;
     t.Start();
     this.Close();
 }
コード例 #57
0
        private void Button_Click_Launch(object sender, RoutedEventArgs e)
        {
            Save();

            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(injectMods));
            t.SetApartmentState(System.Threading.ApartmentState.STA);
            t.Start();
        }
コード例 #58
0
        public void iniciaThread()
        {
            Thread td = new System.Threading.Thread(new System.Threading.ThreadStart(ler));

            td.SetApartmentState(System.Threading.ApartmentState.STA);
            td.IsBackground = true;
            td.Start();
        }
コード例 #59
0
        public ChannelManage()
        {
            InitializeComponent();
            _ChannelManageViewModel                 = new ChannelManageViewModel();
            this.DataContext                        = _ChannelManageViewModel;
            listViewCaptureResults.ItemsSource      = _ListMyCapFaceLogWithImg;
            listViewContIdentifyResults.ItemsSource = _ListIdentifyResults;
            ResetServerRealtimeCapInfo              = new ManualResetEvent(false);
            ResetServerRealtimeCmpInfo              = new ManualResetEvent(false);
            //初始化OCX控件载体
            for (int i = 0; i < 16; i++)
            {
                WindowsFormsHost wfh = new WindowsFormsHost();
                wfh.Tag = null;
                wFHList.Add(wfh);
            }
            //初始化默认分屏
            SetVideoGridScreen(1);
            //打开客户端服务,接收业务服务器上传的实时抓拍和实时识别结果
            Thread ThreadStarServer = new System.Threading.Thread(new ParameterizedThreadStart(StartServer));

            ThreadStarServer.SetApartmentState(ApartmentState.STA);
            ThreadStarServer.Start();
            //域值设置
            int threshold = thirft.QueryThreshold();

            if (threshold == -1)
            {
                _ChannelManageViewModel.SelectedThreshold = Convert.ToInt32(ConfigurationManager.AppSettings["阈值"]) - 1;
            }
            else
            {
                if (Login.ClientType != "1")
                {
                    _ChannelManageViewModel.SelectedThreshold = threshold - 1;
                }
                else
                {
                    double trueThreshold = Math.Sqrt(threshold) * 10;
                    trueThreshold = Math.Round(trueThreshold, 0, MidpointRounding.AwayFromZero);
                    _ChannelManageViewModel.SelectedThreshold = Convert.ToInt32(trueThreshold) - 1;
                }
            }
            //根据客户端类型来修改客户端
            if (Login.ClientType == "1")
            {
                btnAddPassageWay.Visibility    = Visibility.Hidden;
                btnModifyPassageWay.Visibility = Visibility.Hidden;
                btnDeletePassageWay.Visibility = Visibility.Hidden;
                comboAutoSend.Visibility       = Visibility.Hidden;
                comboThreshold.IsEnabled       = false;
                _ChannelManageViewModel.RefreshChannelList();
            }
            if (Login.ClientType == "2")
            {
                comboAutoSend.Visibility = Visibility.Hidden;
            }
        }
コード例 #60
0
ファイル: BOMTool.cs プロジェクト: hanlonal/CSE4982013
 private void iTCapToolStripMenuItem_Click(object sender, EventArgs e)
 {
     closeState = "ITCap";
     System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(RUNITCap));
     t.SetApartmentState(System.Threading.ApartmentState.STA);
     t.Start();
     this.Close();
     return;
 }