示例#1
0
        public void feedMessage(Message message)
        {
            chats.Add(message);
            // Show message on screen
            string msg = "Client ID: " + message.clientID + " said (" + message.timestamp.ToString() + ") :";

            chatBox.AppendText(msg);
            msg = "\n" + message.message + "\n";
            chatBox.AppendText(msg);
            lastMessageNo++;
        }
示例#2
0
 void ReceiveMessage()               // функция приема даных
 {
     byte[] buffer = new byte[1024]; // буфер для приема сообщений от сервера
     for (int i = 0; i < buffer.Length; i++)
     {
         buffer[i] = 0; // чистим буфер заполняя "0"
     }
     for (; ;)          // безконечный цикл
     {
         try
         {
             Client.Receive(buffer);                           // принимаем даные от сервера, записав их в "buffer"
             string message = Encoding.UTF8.GetString(buffer); // декодируем сообщение с "buffer" заннося полученый текст в строку "message"
             int    count   = message.IndexOf(";;;5");         // инициализируем размер сообщения начало и конец строки с помощью функции IndexOF которая будет задавать конец сообщения когда найдет последователость ";;;5" в строке
             if (count == -1)                                  // если IndexOF не сработал, игнорируеем сообщение.
             {
                 continue;
             }
             string Clear_Message = ""; // создаем буфер для отображения сообщения в чате
             for (int i = 0; i < count; i++)
             {
                 Clear_Message += message[i]; // заносим в него уже отформаттированый текст (декодированый, с задаными параметрами начала и конца строки)
             }
             for (int i = 0; i < buffer.Length; i++)
             {
                 buffer[i] = 0;                     // чистим буфер приема сообщений с сервера
             }
             this.Invoke((MethodInvoker) delegate() // ф-ция "this" нужна для возможности получения доступа для потока к элементу формы (окно отображения сообщений)
             {
                 ChatBox.AppendText(Clear_Message); // выводим в чат буфер с отформатированым текстом с помщью фунции "AppendText"
             });
         }
         catch (Exception ex) { }
     }
 }
        public async void enemyStrike()
        {
            updateStuff();
            await sleeper(3);

            bool didStrike = false;

            for (int i = 0; i < noobFighter.possibleMoves.Count(); i++)
            {
                int   index = rand.Next(0, noobFighter.possibleMoves.Count());
                moves move  = noobFighter.possibleMoves[index];
                if (noobFighter.energy - move.cost > -1)
                {
                    EnemyImgBox.Source = new BitmapImage(new Uri(move.spriteLocation));
                    char1.health       = char1.health - move.damage;
                    noobFighter.energy = noobFighter.energy - move.cost;
                    ChatBox.AppendText(noobFighter.name + " used " + move.name + "." + Environment.NewLine);
                    ChatBox.ScrollToEnd();
                    didStrike     = true;
                    userCanStrike = true;
                    break;
                }
                updateStuff();
                await sleeper(2);

                EnemyImgBox.Source = new BitmapImage(new Uri("../CodeDay/Amish ginger.png", UriKind.Relative));
            }
            if (didStrike == false)
            {
                winLose(true);
            }

            updateStuff();
        }
示例#4
0
        private void Network_ChatEventHandler(object sender, ChatEvent e)
        {
            ChatBox.BeginInvoke((MethodInvoker) delegate
            {
                int st = ChatBox.TextLength;
                ChatBox.SelectionFont      = BoldFont;
                ChatBox.SelectionBackColor = Color.DarkCyan;
                ChatBox.AppendText(e.message.OwnerName + ":");

                ChatBox.Select(st, ChatBox.TextLength - st);
                ChatBox.SelectionFont = StdFont;
                ChatBox.DeselectAll();

                st = ChatBox.TextLength;
                ChatBox.AppendText(e.message.Message + "\r\n");
                ChatBox.Select(st, ChatBox.TextLength - st);
                ChatBox.SelectionBackColor = Color.Black;
                ChatBox.DeselectAll();

                ChatBox.ScrollToCaret();

                AddMessage(e.message);
            });

            if (e.message.MessageID == IncrementID)
            {
                ChatBoxMessage.Invoke((MethodInvoker) delegate
                {
                    ChatBoxMessage.Text = "";
                    IncrementID++;
                    ChatBoxMessage.Focus();
                });
            }
        }
示例#5
0
        public async System.Threading.Tasks.Task OpenRoomAsync(string roomId)
        {
            Chromium.SetSettings(roomId);
            var jepa = Chromium.Connect();

            jepa.Height = 720;
            jepa.Width  = 405;

            VideoChatCanvas.Children.Add(jepa);
            chatGrid.Visibility      = Visibility.Visible;
            GraphCanvas.Visibility   = Visibility.Visible;
            ControlCanvas.Visibility = Visibility.Visible;
            leaveButton.Visibility   = Visibility.Visible;
            LobbysCanvas.Visibility  = Visibility.Hidden;
            conferenssionString.Text = $"Конференция №{roomId.Substring(0, 8)}";
            ConferensionString.Text  = $"Чат конференции №{roomId.Substring(0, 8)}";
            ///
            try
            {
                await SocketConnector.InitializeClientAsync();

                SocketConnector.SetSettings(roomId, UserInfo.Name);
                SocketConnector.client.On("chat-message", async response =>
                {
                    var text = JsonConvert.DeserializeObject <JSONmessage[]>(response.ToString());
                    await Dispatcher.BeginInvoke((Action)(() => ChatBox.AppendText($"{text[0].UserId}: {text[0].Message}\n\n")));
                    Console.WriteLine($"{text[0].UserId}: {text[0].Message}");
                });
                chatTextBox.IsReadOnly = (SocketConnector.IsConnected) ? false : true;
            }
            catch { }
        }
示例#6
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            while (chatMessages.Count > 0)
            {
                if (chatMessages[0].name != "" && chatMessages[0].msg != "")
                {
                    realChatBox.SelectionStart  = realChatBox.TextLength;
                    realChatBox.SelectionLength = 0;
                    Font name = new Font(realChatBox.Font.FontFamily, 10, FontStyle.Bold);
                    realChatBox.SelectionFont  = name;
                    realChatBox.SelectionColor = chatMessages[0].color;
                    realChatBox.AppendText(chatMessages[0].name + ": ");

                    realChatBox.SelectionStart  = realChatBox.TextLength;
                    realChatBox.SelectionLength = 0;
                    Font msg = new Font(realChatBox.Font.FontFamily, 8, FontStyle.Regular);
                    realChatBox.SelectionFont  = msg;
                    realChatBox.SelectionColor = Color.Black;
                    realChatBox.AppendText(chatMessages[0].msg);
                }


                ChatBox.AppendText(chatMessages[0].rawMsg);
                chatMessages.RemoveAt(0);
            }
        }
示例#7
0
        /// <summary>
        /// Callback that allows the entry of messages from any user in the game chat.
        /// </summary>
        /// <param name="username"> The username of the user who is sending the incoming message. </param>
        /// <param name="message"> The incoming message. </param>
        public void ReciveMessage(string username, string message)
        {
            string format = "\n" + username + ": " + message;

            ChatBox.AppendText(format);
            ChatBox.ScrollToEnd();
        }
示例#8
0
 private void Btn_Send_Click(object sender, RoutedEventArgs e)
 {
     ChatBox.AppendText(username + ": " + InputBox.Text + "\n");
     Net.TCPClient.SendChatMessage(InputBox.Text);
     InputBox.Text = "";
     ChatBox.ScrollToEnd();
 }
示例#9
0
 private void ClientOnMessageIncomeEvent(string userId, string username, string msg)
 {
     if (!_userColors.ContainsKey(userId))
     {
         ClientOnNewUserJoinedEvent(userId);
     }
     ChatBox.AppendText(username, msg, _userColors[userId]);
 }
示例#10
0
 /// <summary>
 /// Occurs before the KeyDown event
 /// </summary>
 /// <param name="sender">Object that raised the event</param>
 /// <param name="e">Previous key down event info</param>
 private void ChatBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
 {
     // If the key is tab we add a tab character to the chat box
     if (e.KeyCode == Keys.Tab)
     {
         e.IsInputKey = true;
         ChatBox.AppendText("\t");
     }
 }
示例#11
0
 private void MsgBox_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.Enter)
     {
         ChatBox.Text += Environment.NewLine; ChatBox.AppendText(Start_window.username + ": " + MsgBox.Text);
         _tcpClient.Client.Send(Encoding.ASCII.GetBytes(Start_window.username + ": " + MsgBox.Text));
         MsgBox.Text = "";
     }
 }
示例#12
0
 private void SetText(string text)
 {
     if (!Dispatcher.CheckAccess())
     {
         Dispatcher.Invoke(new SetTextCallBack(SetText), text);
         return;
     }
     ChatBox.AppendText(text);
 }
示例#13
0
        private void SendButton_Clicked(object sender, RoutedEventArgs e)
        {
            chatCount += 1;
            ChatsScrollView.ScrollToBottom();
            ChatBox.AppendText($"Вы: {chatTextBox.Text}\n\n");
            SocketConnector.SendMessage(chatTextBox.Text);
            chatTextBox.Text = "";

            //ChatTextBlock.Text = chatTextBox.Text;
        }
示例#14
0
 private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
 {
     lock (client)
     {
         currUser.position = (StarSystem)e.Item.Tag;
         ChatBox.AppendText("Entered system " + currUser.position.name + "\n");
         SendUpdateToServer();
         RefreshForm();
     }
 }
示例#15
0
 private void InputBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
 {
     if (e.Key == System.Windows.Input.Key.Enter)
     {
         ChatBox.AppendText(username + ": " + InputBox.Text + "\n");
         Net.TCPClient.SendChatMessage(InputBox.Text);
         InputBox.Text = "";
         ChatBox.ScrollToEnd();
     }
 }
示例#16
0
 public static void AddMessage(string Message)
 {
     ChatBox.Invoke(new MethodInvoker(delegate {
         // Append new message to the ChatBox.
         ChatBox.AppendText(Message + "\n");
         // Set the current caret position to the end
         ChatBox.SelectionStart = ChatBox.Text.Length;
         // Scroll it automatically
         ChatBox.ScrollToCaret();
     }));
 }
示例#17
0
 private void SafeAppendToChatBox(string text)
 {
     if (ChatBox.InvokeRequired)
     {
         CbCheck c = new CbCheck(SafeAppendToChatBox);
         this.Invoke(c, new object[] { text });
     }
     else
     {
         ChatBox.AppendText(text);
     }
 }
示例#18
0
 private void WriteToChat(string message)
 {
     if (string.IsNullOrEmpty(ChatBox.Text))
     {
         ChatBox.AppendText(message);
     }
     else
     {
         ChatBox.AppendText("\n");
         ChatBox.AppendText(message);
     }
     ChatBox.ScrollToEnd();
 }
示例#19
0
        private void ClickIconChat(object sender, EventArgs e)
        {
            string message = TextBoxChat.Text;

            if (!string.IsNullOrEmpty(message))
            {
                serverChat.SendMessage(GameId, message);

                string format = "\n" + Properties.Resources.You + ": " + message;
                ChatBox.AppendText(format);
                ChatBox.ScrollToEnd();
                TextBoxChat.Clear();
            }
        }
 private void WriteToChat(string time, string from, string message)
 {
     ChatBox.Dispatcher.Invoke(() =>
     {
         if (Settings.ShowTimestamp)
         {
             ChatBox.AppendText($"[{time}] ", Brushes.Gray);
         }
         ChatBox.AppendText($"{from}: ", Brushes.DarkTurquoise);
         ChatBox.AppendText(message, Brushes.PowderBlue);
         ChatBox.AppendText(Environment.NewLine);
         ChatBox.ScrollToEnd();
     });
 }
示例#21
0
 private void print(string msg)
 {
     if (this.InvokeRequired)
     {
         this.Invoke(Printer, msg);
         return;
     }
     if (ChatBox.Text.Length == 0)
     {
         ChatBox.AppendText(msg);
     }
     else
     {
         ChatBox.AppendText(Environment.NewLine + msg);
     }
 }
示例#22
0
        //***************************************************************************************************************
        //
        // Method: AppendMessageToChat
        //
        // Description:
        //    Method for the message receiving thread to call as to append the new message to the chatbox. This also
        //    makes sure to automatically scroll the chatbox to the bottom (newest messages) as it overflows the normal
        //    chatbox area.
        //
        // Arguments:
        //    N/A
        //
        // Return:
        //    N/A
        //
        //***************************************************************************************************************
        private void AppendMessageToChat(String theMessage)
        {
            // Append the received message to the chatbox.
            ChatBox.AppendText(theMessage);

            // Get the component that is currently focused.
            UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

            // Set focus to the chatbox and make sure to scroll to the end of the chatbox.
            ChatBox.Focus();
            ChatBox.CaretIndex = ChatBox.Text.Length;
            ChatBox.ScrollToEnd();

            // Reset the focus to the previous focused component.
            elementWithFocus.Focus();
        }
        private void WriteToChat(string message, Brush color = null)
        {
            if (color == null)
            {
                color = Brushes.DarkGray;
            }

            ChatBox.Dispatcher.Invoke(() =>
            {
                if (Settings.ShowTimestamp)
                {
                    var time = DateTime.Now.ToString("h:mm tt");
                    ChatBox.AppendText($"[{time}] ", Brushes.Gray);
                }
                ChatBox.AppendText(message, color);
                ChatBox.AppendText(Environment.NewLine);
                ChatBox.ScrollToEnd();
            });
        }
示例#24
0
        /// <summary>
        /// Callback invoked when the user takes the turn.
        /// </summary>
        /// <param name="isFirstTurn"> A Boolean value that deremines if it's first turn or not. </param>
        public void IsYourTurn(bool isFirstTurn)
        {
            int numberOfTilesToPlay = 0;
            int count = 0;

            if (isFirstTurn)
            {
                foreach (Image image in TilesPlayer1.Children)
                {
                    if (count == highestTilePosition)
                    {
                        image.AllowDrop            = true;
                        image.Opacity              = 1;
                        image.MouseLeftButtonDown += new MouseButtonEventHandler(TileSelected);
                        break;
                    }
                    count++;
                }
            }
            else
            {
                LookForAPossibleTile(out numberOfTilesToPlay, out int[] tilesToPlay);
                if (numberOfTilesToPlay != 0)
                {
                    EnablePossibleTiles(tilesToPlay);
                }
                else
                {
                    if (TalesInBank > 0)
                    {
                        serverGame.TakeFromTheBank(GameId);
                        TalesInBank     -= 1;
                        TextBoxBank.Text = TalesInBank.ToString();
                    }
                    else
                    {
                        ChatBox.AppendText(Properties.Resources.NoMoreTilesInBank);
                        ChatBox.ScrollToEnd();
                        serverGame.PassTurn(GameId);
                    }
                }
            }
        }
示例#25
0
        private void RunBTN_Click(object sender, EventArgs e)
        {
            if (ReconnectTimer.Enabled == false)
            {
                Reconnect();
                ReconnectTimer.Enabled = true;
                RunBTN.Text            = "Stop";
            }

            else
            {
                if (ReconnectTimer.Enabled == true)
                {
                    ReconnectTimer.Enabled = false;
                    ChatBox.AppendText("\n Disconnected");
                    RunBTN.Text = "Run";
                }
            }
        }
示例#26
0
        private void ClickIconChat(object sender, EventArgs e)
        {
            string message = TextBoxChat.Text;

            if (!string.IsNullOrEmpty(message))
            {
                try
                {
                    server.SendMessage(0, message);

                    string format = "\n" + Properties.Resources.You + ": " + message;
                    ChatBox.AppendText(format);
                    ChatBox.ScrollToEnd();
                    TextBoxChat.Clear();
                }
                catch (CommunicationObjectFaultedException ex)
                {
                    Console.WriteLine(ex.ToString());
                    LabelAlert.Content = Properties.Resources.ServerIsOff;
                }
            }
        }
示例#27
0
 private void OnAlert(ChatAlert alert)
 {
     ChatBox.AppendText(alert.messageToSend + "\n");
     ChatBox.SelectionStart = ChatBox.Text.Length;
     ChatBox.ScrollToCaret();
 }
示例#28
0
 private void btnSend_Click(object sender, EventArgs e)
 {
     ChatBox.ForeColor = Me.Mycolor;
     ChatBox.AppendText(Me.Name + ": " + TextBox.Text);
     ChatBox.AppendText("\n");
 }
示例#29
0
 /// <summary>
 /// Appends some text to the chat log.
 /// </summary>
 /// <param name="text">The text to be added.</param>
 private void appendText(string text)
 {
     ChatBox.AppendText(text);
     ChatBox.ScrollToCaret();
     ChatBox.Refresh();
 }
示例#30
0
        private void Receive_Message()
        {
            int Len;

            byte[] Stream_data = new byte[1024];
            string message     = null;

            try
            {
                Task.Run(() =>
                {
                    while (true)
                    {
                        if (N_stream.CanRead)
                        {
                            Len     = N_stream.Read(Stream_data, 0, Stream_data.Length); //비동기 코드
                            message = Encoding.Default.GetString(Stream_data, 0, Len);

                            if (message.Equals(Packet.Shutdown))
                            {
                                ChatBox.Invoke((MethodInvoker) delegate() {
                                    ChatBox.AppendText("서버와의 연결이 끊어졌습니다.\n");
                                });
                                N_stream.Close();
                                client.Close();
                                goto EXIT;
                            }
                            else if (message.StartsWith("[$") && message.EndsWith("$]"))
                            {
                                List <string> Date_and_Text = message.Split('$').ToList <string>();
                                Date_and_Text.RemoveAt(0);
                                Date_and_Text.RemoveAt(Date_and_Text.Count - 1);//'[', ']'제거
                                if (MessageBox.Show("일정이 왔습니다.\n일정 : " + Date_and_Text[0] + "\n내용 : " + Date_and_Text[1], "공유알림", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    try
                                    {
                                        quary.connection.Open();
                                        quary.command.CommandText = "select Time from " + id + "_scheduler where Time='" + Date_and_Text[0] + "'";
                                        quary.reader = quary.command.ExecuteReader();
                                        if (quary.reader.Read())//일정이 존재하면 덮어씌우기
                                        {
                                            quary.reader.Close();
                                            quary.command.CommandText = "update " + id + "_scheduler set Schedule='" + Date_and_Text[1] + "' where Time='" + Date_and_Text[0] + "'";
                                            quary.command.ExecuteNonQuery();
                                            MessageBox.Show("일정이 수정되었습니다.");
                                        }
                                        else
                                        {
                                            quary.reader.Close();
                                            quary.command.CommandText = "insert into " + id + "_scheduler values ('" + Date_and_Text[0] + "', '" + Date_and_Text[1] + "')";
                                            quary.command.ExecuteNonQuery();
                                            MessageBox.Show("일정이 삽입되었습니다.");
                                        }
                                    }
                                    catch (Exception err) { }
                                    finally
                                    {
                                        quary.connection.Close();
                                    }
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else if (message.Equals(Packet.Approve))
                            {
                                ChatBox.Invoke((MethodInvoker) delegate()
                                {
                                    ChatBox.AppendText("접속성공!\n");
                                });
                            }
                            else if (message.Length >= 1) //한 글자 이상이라면,
                            {
                                ChatBox.Invoke((MethodInvoker) delegate() {
                                    ChatBox.AppendText(message + "\n");
                                });
                            }
                        }
                    }
                    EXIT:;
                });
            }
            catch (SocketException errcode)
            {
                MessageBox.Show(errcode.Message);
            }
        }