/// <summary> /// Таймер игры /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GameTimer_Tick(object sender, EventArgs e) { timer.Text = m + ":" + s; s = s - 1; if (s == -1) { m = m - 1; s = 59; } if (m == -1 && !no_reply) { timer.Text = "Время вышло"; GameTimer.Stop(); // Останавливаем таймер игры EffectTimer.Stop(); // Останавливаем действующие эффекты GlobalTimer.Stop(); // Останавливаем передвижение игроков if (Mouse.mice.Count == 4) { ServerTimer.Stop(); // Прекращаем обмен данных с сервером Server.ConclusionOfGame(); // Подведение итогов Close(); } else if (Mouse.mice.Count == 1) { MessageBox.Show("Время вышло!", "Конец игры"); Close(); } no_reply = true; } }
// set up the timer service for messages that need to be processed in the main RunUO thread for safety reasons public static void StartServerTimer(TimeSpan delay) { if (m_ServerTimer != null) { m_ServerTimer.Stop(); } m_ServerTimer = new ServerTimer(delay); m_ServerTimer.Start(); }
/// <summary> /// Действия после закрытия GameForm /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GameForm_FormClosed(object sender, FormClosedEventArgs e) { no_reply = false; GameTimer.Stop(); // Останавливаем таймер игры EffectTimer.Stop(); // Останавливаем действующие эффекты GlobalTimer.Stop(); // Останавливаем передвижение игроков ServerTimer.Stop(); // Останавливаем обмен данных с сервером MenuForm menu_form = Owner as MenuForm; menu_form.Show(); // Вызываем FormMenu }
private void ReceiveCallback(IAsyncResult ar) { try { // Read data from the remote device. int bytesRead = _clientSocket.EndReceive(ar); // There is something to read if (bytesRead > 0) { // Update the counter of reeived bytes. _receiveBufferCounter += bytesRead; if (_receiveBufferCounter > 0 && _receiveBufferCounter < _bytesToRead) { // I still need to receive data for the current message. // Save what I received up to now, and listen again the socket. Array.Copy(_receiveByteBuffer, 0, _storedByteBuffer, _receiveBufferCounter - bytesRead, bytesRead); // Call the Receive again, to reed more bytes. Receive(_bytesToRead - _receiveBufferCounter); } else if (_receiveBufferCounter == _bytesToRead) { // The counter is equal to _bytesToRead, the read is now complete. // Still need to copy in the buffer what I have just received. Array.Copy(_receiveByteBuffer, 0, _storedByteBuffer, _receiveBufferCounter - bytesRead, bytesRead); // I read the first 2 bytes of a message containing its length if (_receiveBufferCounter == 2) { // Message length is encoded in network byte order (Big Endian), so I need to check if the architecture // of the host is Little Endian, in that case reverse the order of the bytes before decoding if (BitConverter.IsLittleEndian) { Array.Reverse(_storedByteBuffer); } ushort messageLength = BitConverter.ToUInt16(_storedByteBuffer, 0); nextRead = true; Receive(messageLength); } else { // Then I can start processing the data. // Create a string and get the received content of the buffer. string receivedString = Encoding.Default.GetString(_storedByteBuffer); string[] lines = Regex.Split(receivedString, "\n"); if (lines[0].Equals("newwindow")) // newwindows\n<path_exe>\n<nome_finestra>\n<handle>\n<pid>\n<dim_icona>\n<byteicon> { // I have a new window to listen about, and then add the to the ServerModel string exePath = lines[1]; // Create the path and extract the file (program) name. string windowName = lines[2]; int processHandle = Int32.Parse(lines[3]); int processID = Int32.Parse(lines[4]); // Set anyway the image as null. BitmapImage icon = null; if (lines.Length > 6) { // Means that there also information about the image, otherwise there is not int iconDimension = Int32.Parse(lines[5]); // If the iconDimension is < 0, that means that there were some errors: don't even read the rest of the message. if (iconDimension > 0) { // Means that the Icon has been properly sent icon = new BitmapImage(); byte[] imageByte = new byte[iconDimension]; // Compute the index of the start of the byte of the icon, so the already processed bytes. int iconOffset = 0; for (int i = 0; i < 6; i++) { iconOffset += lines[i].Length + 1; } // Take the image byte from the receivedByte, not from the receivedString, because it could have some \n characters. Array.Copy(_storedByteBuffer.Skip(iconOffset).ToArray(), imageByte, iconDimension); // Save the byte as a BitMapImage using (var stream = new MemoryStream(imageByte)) { stream.Position = 0; icon.BeginInit(); icon.CreateOptions = BitmapCreateOptions.PreservePixelFormat; icon.CacheOption = BitmapCacheOption.OnLoad; icon.StreamSource = stream; icon.EndInit(); icon.Freeze(); } } } // Create the processModel with its constructor // Icon can be null ProcessModel newProcessM = new ProcessModel(windowName, exePath, processHandle, processID, icon); // Set the notification message for the GUI. _mainWinWMCaller.NotificationMessage = "Server: " + _serverIpAddress.ToString() + ".\nNew window " + newProcessM.ExePath + " has been created."; // The process must be added in the ListofProcesses of the ServerModel System.Windows.Application.Current.Dispatcher.Invoke((Action) delegate { _processList.Add(newProcessM); }); // Update the process list the of the mainWindowModel. _mainWinWMCaller.RaisePropertyChanged("TheProcessesList"); // Add this process to the applications of the same type AddProcessToApplication(newProcessM); } if (lines[0].Equals("closed")) // closed\n<handle>\n<pid> { // I have received a notification from the server: one window have been closed. // Extract Handle and PID string[] handleAndPID = Regex.Split(lines[1], " "); int handle = Int32.Parse(handleAndPID[0]); int pid = Int32.Parse(handleAndPID[1]); // Remove the Windows from the process lists. Find the process. foreach (ProcessModel proc in _processList) { // Check if the window has the focus (different from null and they have the same handle) if (_focusedProcess != null && _focusedProcess.ProcessWindowHandle.Equals(proc.ProcessWindowHandle)) { // Check if the window has the focus (different from null and they have the same handle) if (_focusedProcess != null && _focusedProcess.ProcessWindowHandle.Equals(proc.ProcessWindowHandle)) { _focusedProcess.PauseWatch(); _focusedProcess = null; } System.Windows.Application.Current.Dispatcher.Invoke((Action) delegate { // Remove the process from the process list. _processList.Remove(proc); // Remove the process from the list of applications. RemoveProcessFromApplications(proc); }); // Set the notification message for the GUI. _mainWinWMCaller.NotificationMessage = "Server: " + _serverIpAddress.ToString() + ".\nProcess " + proc.ExePath + " has been closed."; // Exit the for loop. break; } } } if (lines[0].Equals("focus")) { // I have received a notification, the window with focus has changed. if (lines[1].Equals("nullwindow")) { // There is no focused window. Stop the focus: interrupt a timer. // But only if the focused process already exists if (_focusedProcess != null) { _focusedProcess.PauseWatch(); _focusedProcess.ProcessStatus = ""; _focusedProcess = null; } _mainWinWMCaller.NotificationMessage = "Server: " + _serverIpAddress.ToString() + ".\nFocus set on: null."; } if (lines[1].Equals("windowsoperatingsystem")) { // The focus is hold by the operating system. Stop the focus: interrupt a timer // But only if the focused process already exists if (_focusedProcess != null) { _focusedProcess.PauseWatch(); _focusedProcess.ProcessStatus = ""; _focusedProcess = null; } _mainWinWMCaller.NotificationMessage = "Server: " + _serverIpAddress.ToString() + ".\nFocus set on: Operating System."; } if (lines[1].All(char.IsDigit)) // Check that the string is a number. { // A window holds the focus. int handle = Int32.Parse(lines[1]); int pid = Int32.Parse(lines[2]); // Change the focus: interrupt a timer (if there was one running) and start another. // But only if the focused process already exists if (_focusedProcess != null) { _focusedProcess.PauseWatch(); _focusedProcess.ProcessStatus = ""; } // Find the focused process. foreach (ProcessModel proc in _processList) { if (proc.ProcessWindowHandle == handle) { // Set this process as the focused one. _focusedProcess = proc; // Exit the for loop. break; } } _focusedProcess.RestartWatch(); _focusedProcess.ProcessStatus = "On Focus"; _mainWinWMCaller.NotificationMessage = "Server: " + _serverIpAddress.ToString() + ".\nFocus set on: " + _focusedProcess.ExePath + "."; } } // Set the flag to read next block and go back to listen on the socket. nextRead = true; Receive(2); } } } else if (bytesRead == 0) { // In am in the case of a graceful disconnection, shutdown of the server from the serverside. // Stop the Check Connection Timer ServerTimer.Stop(); // Close the connection with the server. The disconnect function calls the CloseClient, the Remove server, and the removeProcessesFromApplication. _mainWinWMCaller.DisconnectFromServer(this.ServerIpAddress); // Close the connection with the server. The disconnect function calls the CloseClient, the Remove server, and the removeProcessesFromApplication. System.Windows.Application.Current.Dispatcher.Invoke((Action) delegate { // Open the Error Window Views.ErrorWindowView errView = new Views.ErrorWindowView(); ErrorWindowViewModel errWindViewModel = new ErrorWindowViewModel("Connessione interrotta dal server " + this.ServerIpAddress.ToString() + "."); errWindViewModel.ClosingRequest += errView.Close; errView.DataContext = errWindViewModel; errView.Show(); }); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
/// <summary></summary> public static async Task Main(string[] args) { // NOTE: このプログラム中では社員データ(もしくはユーザデータ)の同期を行わせないため, // 外部より任意の時点でそれらデータの同期を行わせる必要がある. // 蓄積したデータを対象として追加及び削除などの更新処理を行わせない. // データベース設定 Db.DbFactory.GetInstance( await DbSettings.LoadAsync("db.conf")); try { readerSettings = await Settings.LoadAsync("settings.conf"); } catch (Exception) { // 設定ファイルが存在しない場合や xml パースに失敗. readerSettings = new Settings() { Id = Guid.NewGuid(), Hostname = "192.168.100.64" }; } finally { if (readerSettings != null) { readerId = readerSettings.Id; insideNumbers = readerSettings.InsideAntennas; outsideNumbers = readerSettings.OutsideAntennas; } } try { // データベースへ該当リーダのデータを追加 await entleaving.Db.DAO.Reader.UpsertAsync( readerSettings.Id, readerSettings.Hostname, null, null); } catch { throw; } // FreeeAPI アクセストーク取得 if (!File.Exists("access_token.json")) { throw new FileNotFoundException( message: null, fileName: "access_token.json"); } var freeeToken = await entleaving.freee.ResponseToken.LoadAsync("access_token.json"); var freeeAPI = entleaving.freee.FreeeAPIFactory.GetInstance(freeeToken.AccessToken); freeeAPI.Token = freeeToken; try { var clientInfo = await entleaving.freee.FreeeAPIClientInfo.LoadAsync("freee_client.conf"); freeeAPI.ClientId = clientInfo.Id; freeeAPI.ClientSecret = clientInfo.Secret; } catch { Console.Error.WriteLine($"Warning # Freeee API のクライアント情報の取得に失敗. アクセストークンの更新が行えない可能性があります."); } // UHF 帯 RFID リーダ動作開始 IUhfReader reader = new R420Reader(); reader.ConnectionLost += OnUhfReaderConnectionLost; reader.DetectedTag += OnUhfReaderDetectedTag; reader.Settings = readerSettings; reader.Open(); reader.Start(); Console.CancelKeyPress += OnCancelKeyPress; intervalTimer.Elapsed += OnIntervalTimerElapsed; intervalTimer.Start(); eventHandler = new EventWaitHandle( initialState: false, mode: EventResetMode.ManualReset); eventHandler.WaitOne(); reader.DetectedTag -= OnUhfReaderDetectedTag; intervalTimer.Elapsed -= OnIntervalTimerElapsed; intervalTimer.Stop(); #if DEBUG Console.Error.WriteLine($"Debug Exit."); #endif reader.Stop(); reader.Close(); }