0

We have 2 windows open, like a chat

enter image description here

This is what the textBox and the button looks like:

private void textBox_chat_TextChanged(object sender, TextChangedEventArgs e)
{
}

private void button_enviar_Click(object sender, RoutedEventArgs e)
{
    string chatMessage = textBox_chat.Text;
}

I would like to know how can I send information insered in a textbox by pressing the button "button_enviar". And to be printed to the other window. I have been looking things like Application.Current.Windows... but still don't found the way to make it.

My code looks actually like this:

MainWindow

   namespace WpfApplication1
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }

            // automatic code generated by the button
            private void button_entrar_Click(object sender, RoutedEventArgs e)
            {
                // we catch the taxt input in the texBox
                string userLoginName = textBox_pantalla_inicial.Text;

                // We call the chat window
                Window window1 = new Window1();
                // we put the user name as the title of the chat window
                window1.Title = userLoginName;
                // show the chat window
                window1.Show();            
            }       
        }
    }

ChatWindow

namespace WpfApplication1
{
    /// <summary>
    /// Lógica de interacción para Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            // inicialize chatWindow
            InitializeComponent();            
        }

        private void textBox_chat_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void button_enviar_Click(object sender, RoutedEventArgs e)
        {
            string chatMessage = textBox_chat.Text;

        }       

        private void button_erase_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
Qu4k3
  • 185
  • 3
  • 16
  • You could look at hosting a WCF service inside your applications and calling the service to display messages. – Rick S Dec 02 '15 at 16:02
  • WCF - Windows Communication Foundation https://msdn.microsoft.com/en-us/library/ms731082(v=vs.110).aspx Look up tutorials on chat in .NET – paparazzo Dec 02 '15 at 16:03
  • Thanks for your feedback, but need a solution to work completely in local... – Qu4k3 Dec 02 '15 at 16:06
  • Are both these windows part of a single running application, or are you asking about transferring data between two running processes? The solution provided will be extremely different depending on what you are trying to do. – Russ Dec 02 '15 at 16:06
  • @Russ I have a main window where you write the user name: "user_1" and it opens the window showed in the picture. I can write another user: "user_2" on the main window and i wil have 2 chat windows. The question is send information between this 2 chat windows – Qu4k3 Dec 02 '15 at 16:08
  • Are both windows part of the same running process, or are these run from two separate processes? In other words, does your main window open both the chat windows, or do you have to start a separate application to get the second chat window? – Russ Dec 02 '15 at 16:10
  • @Russ Ahh sorry, yes, my main window can open 1 or more chat windows without having to restart it. – Qu4k3 Dec 02 '15 at 16:13
  • use an event in one common class and raise it on messages update from the child , in addition register to it on the child views for updates – ZSH Dec 02 '15 at 16:15
  • 1
    This question is basically how to set value/access control/exchange data between two windows. Was asked many times: e.g. [click](http://stackoverflow.com/q/13644114/1997232), [click](http://stackoverflow.com/q/7222837/1997232), [click](http://stackoverflow.com/q/25268972/1997232) ... – Sinatr Dec 02 '15 at 16:22
  • @Sinatr Thanks for your feedback, your first link is one of the things I was looking "Application.Current.Windows". I think is the solution but I don't really know how to use it. – Qu4k3 Dec 02 '15 at 16:28
  • Two Windows in one application is not a chat. – paparazzo Dec 02 '15 at 17:08
  • @Frisbee it's a chat exercice not a real functional chat, later it will be between 2 diferent lapdops. – Qu4k3 Dec 02 '15 at 17:14
  • The stated question is not a chat. To characterize it as a chat leads to answers and comments like WPF. – paparazzo Dec 02 '15 at 17:17
  • @Frisbee yeah :) but i never said it's a chat i just said that we have windows "like a chat" to be easier for you to understand the function... write a message and send it. – Qu4k3 Dec 02 '15 at 17:21
  • @Quake654 You are new user and it did not in any way make it easier to understand. You even tagged it chat. The functional need is to say data across windows in an application. – paparazzo Dec 02 '15 at 23:41

3 Answers3

2

This is how I would do :

public partial class ChatWindow : Window
{

    private Client client;
    public ChatWindow(Client _client)
    {
        InitializeComponent();
        client = _client;
        this.Title = client.Name + " chat";
        client.MessageReceived += OnMessageReceived;


        this.Loaded += OnLoaded;
    }

    public void OnMessageReceived(object sender, MessageReceivedArgs e)
    {
        chatControl.Text += e.Sender.Name+": "+ e.Message;
    }

    private void OnLoaded(object sender, EventArgs e)
    {
        client.Send("client " + client.Name + " is loaded!");
    }


}


public class Client{

    public string Name { get; set; }
    public Chat chat{get;set;}



    public Client(string name)
    {
        Name = name;
    }

    public delegate void MessageReceivedEventHandler(object sender, MessageReceivedArgs e);

    public event MessageReceivedEventHandler MessageReceived;

    private void RaiseMessageReceivedEvent(Client sender, string message)
    {
        MessageReceivedArgs e = new MessageReceivedArgs(sender,message);
        if (MessageReceived != null)
            MessageReceived(this, e);
    }

    public void MessageReceivedFromChat(Client sender,string message)
    {
        RaiseMessageReceivedEvent(sender,message);
    }

    public void Send(string message)
    {
        chat.SendMessage(this, message);
    }




}

public class MessageReceivedArgs : EventArgs
{
    public string Message { get; set; }
    public Client Sender { get; set; }
    public MessageReceivedArgs(Client sender,string message)
    {
        Message = message;
        Sender = sender;
    }
}


public class Chat
{
    private List<Client> clients;

    public Chat()
    {
        clients = new List<Client>();
    }

    public void AddClient(Client client)
    {
        client.chat = this;
        clients.Add(client);
    }

    public void RemoveClient(Client client)
    {
        client.chat = null;
        clients.Remove(client);
    }

    public void SendMessage(Client sender, string message)
    {
        foreach(Client client in clients){
            if (client != sender)
            {
                client.MessageReceivedFromChat(sender, message);
            }

        }
    }

}

Create objects :

        Chat chat = new Chat();
        Client jacques = new Client("jacques");
        Client Pierre = new Client("Pierre");
        chat.AddClient(jacques);
        chat.AddClient(Pierre);

        ChatWindow cw = new ChatWindow(jacques);
        cw.Show();
        ChatWindow cw1 = new ChatWindow(Pierre);
        cw1.Show();
KANAX
  • 275
  • 2
  • 13
1

First, you should look into binding with XAML, such as here. That way in your C# code, you won't need to care about the UI controls used--and you can easily change those controls in the XAML if you don't like something or want to improve your window.

You only need to think of your MainWindow and ChatWindow as objects. There are many ways you can make this work. One of the simplest ways is to have an event in your chat window that your main window subscribes to when it creates the chat window. Whenever a user enters his message, the chat window raises the event and passes the text through arguments in the event, which the main window catches and then can call a method (or set a property) in all the chat windows it is tracking so that the message gets passed to all chat windows.

A simple example (free-typed, not tested):

public class MainWindow : Window
{
    List<ChatWindow> chatWindows = new List<ChatWindow>();
    public void AddChatWindow()
    {
        ChatWindow win = new ChatWindow();
        win.NewMessage += MessageReceived;
        win.Show();
        chatWindows.Add(win);
    }
    void MessageReceived(object sender, MessageEventArgs e)
    {
        ChatWindow me = sender as ChatWindow;
        if (me != null)
        {
            foreach (ChatWindow win in chatWindows)
            {
                if (win != me)
                {
                    win.Add(e.Message);
                }
            }
        }
    }
}

public class ChatWindow : Window
{
    public event EventHandler<MessageEventArgs> NewMessage;

    public void Add(string message)
    {
        Messsage += message;
    }
    public void UpdateText(string text)
    {
        if (NewMessage != null)
        {
            NewMessage(this, new MessageEventArgs(Message = text));
        }
    }
    public string Message {get;set;}
}
public class MessageEventArgs : EventArgs
{
     public string Message{get;set;}
}
Russ
  • 4,091
  • 21
  • 32
  • I just actualize my post with the code i have, your post is really close to mine, I will apreciate if you can make a look to my code. – Qu4k3 Dec 02 '15 at 16:41
  • Thanks a lot for your help, it has helped me to clarify my doubts! – Qu4k3 Dec 02 '15 at 17:29
1

I set a little example code that used an event:

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    ChatMsgDispacher _chatMsgDispacher = new ChatMsgDispacher();
    public ChatChild GetNewChat()
    {
        var child = new ChatChild(); //or where you create the child
        child.SetMsgDispacher(_chatMsgDispacher);
        return child;
    }
}

public class ChatMsgDispacher
{
    public delegate void ChatMsgDelegate(string msg);
    public event ChatMsgDelegate MessageUpdate;

    public void Update(string msg)
    {
        if (MessageUpdate != null)
        {
            MessageUpdate(msg);
        }
    }
}


public class ChatChild
{
    private ChatMsgDispacher _msgDispacher;

    public void SetMsgDispacher(ChatMsgDispacher msgDispacher)
    {
        _msgDispacher = msgDispacher;
        _msgDispacher.MessageUpdate += MsgDispacher_MessageUpdate;
    }

    void MsgDispacher_MessageUpdate(string msg)
    {
        //add the msg in the child view
    }

    private void button_enviar_Click(object sender, RoutedEventArgs e)
    {
        string chatMessage = textBox_chat.Text;
        _msgDispacher.Update(chatMessage);
    }
}
ZSH
  • 905
  • 5
  • 15