How to make each user have a different color message

I built an instant messenger and now want to make each user have a dif

Page 1 of 1

1 Replies - 2867 Views - Last Post: 17 July 2009 - 11:27 PM Rate Topic: -----

#1 colorodo13  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 16-February 09

How to make each user have a different color message

Post icon  Posted 17 July 2009 - 08:56 AM

With the code i have written can someone tell me how to make each user of the chat room have a different color message(text color) and were to place the code to do that. Here is the code below. I hope someone can help.
Imports System.Net.Sockets
Imports System.IO
Imports System.Runtime.InteropServices

Public Class Form1
	'---get own IP address
	Dim ips As Net.IPHostEntry = _
	   Net.Dns.Resolve(Net.Dns.GetHostName())

	'---port nos and server IP address
	Const PORTNO As Integer = 500
	Const FTPPORTNO As Integer = 501
	Const SERVERIP As String = "192.168.0.59"

	Dim client As TcpClient
	'--used for sending and receiving data
	Dim data() As Byte

	'---for FTP use 
	Dim fs As System.IO.FileStream
	Dim filename As String
	Dim fullfilename As String
	'--Sign in to server---
	Private Sub btnSignIn_Click( _
	   ByVal sender As System.Object, _
	   ByVal e As System.EventArgs) _
	   Handles btnSignIn.Click
		If btnSignIn.Text = "Sign In" Then

			'---Sign in to the server
			Try
				client = New TcpClient
				' client.NoDelay = True

				'---connect to the server
				client.Connect(SERVERIP, PORTNO)
				ReDim data(client.ReceiveBufferSize - 1)
				'---inform the server of your nick name---
				' e.g. [Join][User1]
				SendMessage("[Join][" & txtNick.Text & "]")

				'---begin reading data asynchronously from 
				'the server
				client.GetStream.BeginRead( _
				   data, 0, CInt(client.ReceiveBufferSize), _
				   AddressOf ReceiveMessage, Nothing)

				'---change the button and textbox
				btnSignIn.Text = "Sign Out"
				btnSend.Enabled = True
				txtNick.Enabled = False

				'---get all users connected
				' e.g. [Usrs]
				System.Threading.Thread.Sleep(500)
				SendMessage("[Users]")

			Catch ex As Exception
				MsgBox(ex.ToString)
			End Try
		Else
			'---Sign off from the server
			Disconnect()
			lbUsers.Items.Clear()

			'---change the button and textbox
			btnSignIn.Text = "Sign In"
			btnSend.Enabled = False
			txtNick.Enabled = True
		End If
	End Sub
	'---Send Button
	Private Sub btnSend_Click( _
	   ByVal sender As System.Object, _
	   ByVal e As System.EventArgs) _
	   Handles btnSend.Click
		'e.g. [Talk][User1,User2,User3,etc]User1>Hello world!

		'---select users to chat
		If lbUsers.SelectedItems.Count < 1 Then
			MsgBox("You must select who to chat with.")
			Exit Sub
		End If

		'---formulate the message
		Dim Message As String = "[Talk]["

		'---check who to chat with
		Dim user As Object
		For Each user In lbUsers.SelectedItems
			Message += user & ","
		Next
		Message += "]" & txtNick.Text & ">" & txtMessage.Text

		'---update the message history
		txtMessageHistory.Text += txtNick.Text & _
		">" & txtMessage.Text & vbCrLf

		'---send message
		SendMessage(Message)
		txtMessage.Clear()
	End Sub
	'TheSendMessage() subroutine, used in the code above, allows the client to send a message to the server: 

	'---Sends the message to the server
	Public Sub SendMessage(ByVal message As String)
		Try
			'---send the text
			Dim ns As System.Net.Sockets.NetworkStream
			SyncLock client.GetStream
				ns = client.GetStream
				Dim bytesToSend As Byte() = _
				System.Text.Encoding. _
				ASCII.GetBytes(message)

				'---sends the text---
				ns.Write(bytesToSend, 0, bytesToSend.Length)
				ns.Flush()
			End SyncLock
		Catch ex As Exception

		End Try
		MsgBox(ToString)
	End Sub

	'---Receives a message from the server
	Public Sub ReceiveMessage(ByVal ar As IAsyncResult)
		'Call using something like
		FlashIcon(MyBase.Handle, FLASHW_TRAY + FLASHW_TIMERNOFG)

		Try
			Dim bytesRead As Integer
			bytesRead = client.GetStream.EndRead(ar)
			If bytesRead < 1 Then
				Exit Sub
			Else
				Dim messageReceived As String = _
				System.Text.Encoding.ASCII.GetString( _
				data, 0, bytesRead)

				'---update the message history
				Dim para() As Object = {messageReceived}
				Me.Invoke(New delUpdateHistory(AddressOf _
				Me.UpdateHistory), para)
			End If

			'---continue reading for more data
			client.GetStream.BeginRead(data, 0, _
			CInt(client.ReceiveBufferSize), _
			AddressOf ReceiveMessage, Nothing)

		Catch ex As Exception
			' MsgBox(ex.ToString)
		End Try
	End Sub
	'---delegate to update the textboxes in the main thread
	Public Delegate Sub delUpdateHistory(ByVal str As String)
	Private Sub Form1_FormClosing( _
  ByVal sender As Object, _
  ByVal e As System.Windows.Forms.FormClosingEventArgs) _
  Handles Me.FormClosing
		Disconnect()
	End Sub
	Public Sub UpdateHistory(ByVal str As String)
		If str.StartsWith("[Join]") Then
			'e.g. [Join][User1]

			'---extract user's name
			Dim nameLength As Integer = str.IndexOf("]", 6)

			'---display in the ListBox
			lbUsers.Items.Add(str.Substring(7, _
			nameLength - 7))

			Exit Sub

		ElseIf str.StartsWith("[Left]") Then
			'e.g. [Left][User1]

			'---extract user's name
			Dim nameLength As Integer = str.IndexOf("]", 6)

			'---remove the user from the listbox
			Try
				lbUsers.Items.RemoveAt( _
				lbUsers.Items.IndexOf( _
				str.Substring(7, nameLength - 7)))

			Catch ex As Exception
			End Try
			Exit Sub

		ElseIf str.StartsWith("[Usrs]") Then
			'e.g. [Usrs][User1,User2,User3,etc]

			'---extract the user names
			Dim users() As String = _
			   str.Substring(7, str.Length - 8).Split(",")

			Dim user As String
			lbUsers.Items.Clear()
			'---add the user to ListBox
			For Each user In users
				lbUsers.Items.Add(user)
			Next
			'---remove the last empty user
			lbUsers.Items.RemoveAt(lbUsers.Items.Count - 1)
			Exit Sub

		ElseIf str.StartsWith("[File]") Then
			'e.g. [File][User1][Filename.ext]

			'---get user name
			Dim users() As String = _
			str.Substring(7, str.IndexOf("]", 7) _
			- 7).Split(",")

			'---extract file name
			Dim index As Integer = str.IndexOf("]", 7) + 2
			Dim filename As String = str.Substring(index, _
			str.Length - index - 3)

			'---prompt the user
			Dim response As MsgBoxResult
			response = MsgBox( _
			"Do you want to download the file " & _
			filename, MsgBoxStyle.YesNo)

			'---proceed with download
			If response = MsgBoxResult.Yes Then
				'---tell the client that he can proceed to 
				'send the file
				' e.g. [Send_File][User1,User2]
				SendMessage("[Send_File][" & users(0) & "," _
				& txtNick.Text & "]")

				'---start the FTP process
				FTP_Receive(filename)
			End If
			Exit Sub

		ElseIf str.StartsWith("[Send_File]") Then
			'e.g. [Send_File][1.2.3.4]

			'---extract the IP address of file recipient
			Dim userIP As String = _
			str.Substring(12, str.Length - 15)

			'start the FTP process
			FTP_Send(fullfilename, userIP)
			Exit Sub

		ElseIf str.StartsWith("[Talk]") Then
			'e.g. [Talk][User1]Hello!

			'---display the message in the textbox
			str = str.Substring(str.IndexOf("]", 7) + 1)
			txtMessageHistory.AppendText(str)
		End If

	End Sub
	'---disconnect from the server
	Public Sub Disconnect()
		Try
			client.GetStream.Close()
			client.Close()
		Catch ex As Exception
		End Try
	End Sub
	'---Send File button
	Private Sub btnFTP_Click( _
	   ByVal sender As System.Object, _
	   ByVal e As System.EventArgs) Handles btnFTP.Click

		'---formulate the message
		'---e.g. [FILE][User1,User2,User3,][Filename.ext]
		Dim Message As String = "[File][" & _
		txtNick.Text & ","

		Dim user As Object
		If lbUsers.SelectedItems.Count < 1 Then
			MsgBox("You must select who to send to.")
			Exit Sub
		End If

		'---check who to send to
		For Each user In lbUsers.SelectedItems
			Message += user & ","
		Next

		'---select the file to send
		Dim openFileDialog1 As New OpenFileDialog()

		openFileDialog1.InitialDirectory = "c:\"
		openFileDialog1.Filter = _
		"txt files (*.txt)|*.txt|All files (*.*)|*.*"

		openFileDialog1.FilterIndex = 2
		openFileDialog1.RestoreDirectory = True

		If openFileDialog1.ShowDialog() = _
		DialogResult.OK Then
			fullfilename = openFileDialog1.FileName

			filename = _
			fullfilename.Substring( _
			fullfilename.LastIndexOf("\") + 1)

			Message += "][" & filename & "]"
			SendMessage(Message)
		End If
		'---FTP process - Send file
	End Sub
	Public Sub FTP_Send( _
	   ByVal filename As String, _
	   ByVal recipientIP As String)

		'---connect to the recipient
		Dim tcpClient As New System.Net.Sockets.TcpClient
		tcpClient.Connect(recipientIP, FTPPORTNO)
		Dim BufferSize As Integer = _
		tcpClient.ReceiveBufferSize
		Dim nws As NetworkStream = tcpClient.GetStream

		'---open the file
		Dim fs As FileStream
		fs = New FileStream(filename, FileMode.Open, _
		FileAccess.Read)

		Dim bytesToSend(fs.Length - 1) As Byte
		Dim numBytesRead As Integer = fs.Read(bytesToSend, _
		0, bytesToSend.Length)

		Dim totalBytes As Integer = 0
		For i As Integer = 0 To fs.Length \ BufferSize
			'---send the file
			If fs.Length - (i * BufferSize) > BufferSize Then
				nws.Write(bytesToSend, i * BufferSize, _
				BufferSize)
				totalBytes += BufferSize
			Else
				nws.Write(bytesToSend, i * _
				   BufferSize, fs.Length - (i * BufferSize))
				totalBytes += fs.Length - (i * BufferSize)
			End If
			'--update the status label
			ToolStripStatusLabel1.Text = _
			   "Sending " & totalBytes & " bytes...."
			Application.DoEvents()
		Next
		ToolStripStatusLabel1.Text = _
		   "Sending " & totalBytes & " bytes....Done."
		fs.Close()
		tcpClient.Close()
		'---FTP Process = Receive Files
	End Sub
	Public Sub FTP_Receive(ByVal filename As String)
		'Call using something like
		FlashIcon(MyBase.Handle, FLASHW_TRAY + FLASHW_TIMERNOFG)

		Try
			'---get the local IP address
			Dim localAdd As System.Net.IPAddress = _
			System.Net.IPAddress. _
			Parse(ips.AddressList(0).ToString)

			'---start listening for incoming connection
			Dim listener As New  _
			   System.Net.Sockets.TcpListener( _
			   localAdd, FTPPORTNO)
			listener.Start()

			'---read incoming stream
			Dim tcpClient As TcpClient = _
			listener.AcceptTcpClient()
			Dim nws As NetworkStream = tcpClient.GetStream

			'---delete the file if it exists
			If File.Exists("c:\temp\" & filename) Then
				File.Delete("c:\temp\" & filename)
			End If

			'---create the file
			fs = New System.IO.FileStream("c:\temp\" & _
			filename, _
			   FileMode.Append, FileAccess.Write)

			Dim counter As Integer = 0
			Dim totalBytes As Integer = 0
			Do
				'---read the incoming data
				Dim bytesRead As Integer = _
					nws.Read(data, 0, _
					tcpClient.ReceiveBufferSize)
				totalBytes += bytesRead
				fs.Write(data, 0, bytesRead)

				'--update the status label
				ToolStripStatusLabel1.Text = "Receiving " & _
				totalBytes & " bytes...."
				Application.DoEvents()
				System.Threading.Thread.Sleep(200)
				counter += 1
			Loop Until Not nws.DataAvailable
			ToolStripStatusLabel1.Text = "Receiving " & _
			totalBytes & " bytes....Done."
			fs.Close()
			tcpClient.Close()
			listener.Stop()

		Catch ex As Exception
			MsgBox(ex.ToString)
		End Try

	End Sub

	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

	End Sub
	Public Structure FLASHWINFO
		Public cbSize As Int32
		Public hwnd As IntPtr
		Public dwFlags As Int32
		Public uCount As Int32
		Public dwTimeout As Int32
	End Structure

	Private Declare Function FlashWindowEx Lib "user32.dll" (ByRef pfwi As FLASHWINFO) As Int32

	Public Const FLASHW_STOP = 0		' Stop flashing. The system restores the window to its original state. 
	Public Const FLASHW_CAPTION = &H1   ' Flash the window caption. 
	Public Const FLASHW_TRAY = &H2	  ' Flash the taskbar button.
	Public Const FLASHW_ALL = &H3	   ' Flash both the window caption and taskbar button. 
	Public Const FLASHW_TIMER = &H4	 ' Flash continuously, until the FLASHW_STOP flag is set. 
	Public Const FLASHW_TIMERNOFG = &HC ' Flash continuously until the window comes to the foreground. 

	Public Sub FlashIcon(ByVal Handle%, ByVal Flags%)
		Dim flash As New FLASHWINFO
		flash.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(flash) '/// size of structure in bytes
		flash.hwnd = Handle '/// Handle to the window to be flashed
		flash.dwFlags = Flags
		flash.dwTimeout = 500 '/// speed of flashes in MilliSeconds ( can be left out )
		FlashWindowEx(flash) '/// flash the window 
	End Sub


End Class



Is This A Good Question/Topic? 0
  • +

Replies To: How to make each user have a different color message

#2 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4424
  • View blog
  • Posts: 12,293
  • Joined: 18-April 07

Re: How to make each user have a different color message

Posted 17 July 2009 - 11:27 PM

Well there are two methods that immediately come to mind and which direction you go depends on your design. The first method would be for allowing people to pass along whatever color they want by putting in "color codes" in with their text. This idea comes back from the days of mIRC and the IRC chat room where people could color text they send to others by including a ctrl + k combination to enter a special character, specify the color number and hit ctrl +k again to tell it when to end the color. Much like tags are used in HTML.

The second method is for assigning colors to others on the receiving user's screen only, oblivious to the actual user sending the text. This involves simply determining which users are connected and keeping track (like in an array) of which user has which color. Whenever you read in data from that person, look up their color, change the font color of the text and THEN add it to the screen. Ideally you will want to use a richedittextbox control for this formatting of colors (and possibly other formatting features like italics or underline).

:)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1