Beispiel #1
0
        delegate void PegaTexto(string text); //Cria um delegate que será um "ponteiro de função"

        private void GravaTexto(string t)
        {
            //Se o controle tbRecebido foi criado em uma thread diferente daquela
            //que está executando este método, uma instância do delegate deve ser criada
            //referenciando o método atual (GravaTexto).
            //Em seguida o método Invoke executa o delegate, que faz com o método SetTexto
            //passe a ser executado na thread que criou o controle tbRecebido, e a
            //propriedade t passe a ser definida diretamente.
            try
            {
                if (this.tbRecebido.InvokeRequired) //cruzamento de threds
                {
                    #region
                    //InvokeRequired retorna "true" se o Handle (identificador) do controle (tbRecebido) foi criado em
                    //uma thread (segmento) diferente da thread que fez a chamada do teste (indicando que você
                    //deve fazer chamadas para o controle através do método invoke (invocar)).

                    //Se o ID da thread principal (interface gráfica) for diferente
                    //de quem está chamando a função, então InvokeRequired retorna TRUE

                    //InvokeRequired compara o "thread ID" da thread chamadora
                    //com o da thread criadora.
                    //Se eles forem diferentes, ele retorna true.
                    #endregion
                    //Instancia o delegate do tipo PegaTexto
                    PegaTexto d = new PegaTexto(GravaTexto);
                    #region
                    //Em seguida é passado ao delegate o ponteiro da função
                    //para que posteriormente possamos invocar (Invoke) o método SetTexto
                    //dentro da thread Principal, portando na segunta execução os IDs
                    //são iguais, fato que permite a atribuição de valores na thread
                    //principal.

                    /*Executes the specified delegate, on the thread that owns the control's
                     * underlying window handle, with the specified list of arguments.
                     *
                     * Executa o delegate (representante) especificado, na thread que possui o
                     * identificador do controle subjacente janela (this), com a lista de
                     * argumentos especificada.
                     */
                    #endregion
                    this.Invoke(d, new object[] { t });
                }
                else
                {
                    //Para mostrar em string
                    //this.tbRecebido.Text += t + Environment.NewLine;  //Acrescenta string e linha
                    this.tbRecebido.AppendText(t + Environment.NewLine);    //Acrescenta string, linha e faz scroll automático

                    //Para mostrar em hexa
                    if (cbHexaEspaço.Checked)
                    {
                        StringBuilder sb = new StringBuilder(t.Length * 3);//dois cracteres + um espaço
                        foreach (byte b in t)
                        {
                            sb.AppendFormat("{0:x2} ", b);
                        }
                        //tbRecebidoH.Text += sb.ToString() + Environment.NewLine;    //Acrescenta string e linha
                        tbRecebidoH.AppendText(sb.ToString() + Environment.NewLine);    //Acrescenta string, linha e faz scroll automático
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder(t.Length * 2);//dois cracteres
                        foreach (byte b in t)
                        {
                            sb.AppendFormat("{0:x2}", b);
                        }
                        //tbRecebidoH.Text += sb.ToString() + Environment.NewLine;    //Acrescenta string e linha
                        tbRecebidoH.AppendText(sb.ToString() + Environment.NewLine);    //Acrescenta string, linha e faz scroll automático
                    }
                }
            }
            catch
            { }
        }
Beispiel #2
0
        delegate void PegaTexto(string text); //Cria um delegate que será um "ponteiro de função"

        private void GravaTexto(string t)
        {
            //Se o controle tbRecebido foi criado em uma thread diferente daquela
            //que está executando este método, uma instância do delegate deve ser criada
            //referenciando o método atual (GravaTexto).
            //Em seguida o método Invoke executa o delegate, que faz com o método SetTexto
            //passe a ser executado na thread que criou o controle tbRecebido, e a
            //propriedade t passe a ser definida diretamente.
            try
            {
                if (this.tbRecebido.InvokeRequired) //cruzamento de threads
                {
                    #region
                    //InvokeRequired retorna "true" se o Handle (identificador) do controle (tbRecebido) foi criado em
                    //uma thread (segmento) diferente da thread que fez a chamada do teste (indicando que você
                    //deve fazer chamadas para o controle através do método invoke (invocar)).

                    //Se o ID da thread principal (interface gráfica) for diferente
                    //de quem está chamando a função, então InvokeRequired retorna TRUE

                    //InvokeRequired compara o "thread ID" da thread chamadora
                    //com o da thread criadora.
                    //Se eles forem diferentes, ele retorna true.
                    #endregion
                    //Instancia o delegate do tipo PegaTexto
                    PegaTexto d = new PegaTexto(GravaTexto);
                    #region
                    //Em seguida é passado ao delegate o ponteiro da função
                    //para que posteriormente possamos invocar (Invoke) o método SetTexto
                    //dentro da thread Principal, portando na segunta execução os IDs
                    //são iguais, fato que permite a atribuição de valores na thread
                    //principal.

                    /*Executes the specified delegate, on the thread that owns the control's
                     * underlying window handle, with the specified list of arguments.
                     *
                     * Executa o delegate (representante) especificado, na thread que possui o
                     * identificador do controle subjacente janela (this), com a lista de
                     * argumentos especificada.
                     */
                    #endregion
                    this.Invoke(d, new object[] { t });
                }
                else
                {
                    char[] c     = t.ToCharArray();
                    bool   Enter = false;
                    string str   = ""; // String que irá receber a conversão
                    //System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();    //Só aceita 7 bits por char
                    foreach (var b in c)
                    {
                        Enter = false;
                        //str += char.ConvertFromUtf32(b).ToString(); //Aceita 8 bits por char (consegue representar acentos, cedilha e til)
                        str += Convert.ToChar(b).ToString();        //Aceita 8 bits por char (consegue representar acentos, cedilha e til)
                        if (cbEnter.Checked)
                        {
                            if ((b == 0x0D) || (b == 0x0A))
                            {
                                str  += Environment.NewLine;
                                Enter = true;                       //Evita um duplo enter quando finaliza a string no TextBox
                            }
                        }
                    }
                    //Para mostrar em string
                    //str = enc.GetString(pac);
                    if (Enter)
                    {
                        tbRecebido.AppendText(str);
                    }
                    else
                    {
                        //tbRecebido.Text += str + Environment.NewLine;    //Acrescenta string e linha
                        tbRecebido.AppendText(str + Environment.NewLine);    //Acrescenta string, linha e faz scroll automático
                    }
                    //Para mostrar em hexa
                    if (cbHexaEspaço.Checked)
                    {
                        StringBuilder sb = new StringBuilder(c.Length * 3);//dois cracteres + um espaço
                        foreach (byte b in c)
                        {
                            sb.AppendFormat("{0:x2} ", b);
                            if (cbEnter.Checked)
                            {
                                if ((b == 0x0D) || (b == 0x0A))
                                {
                                    sb.Append(Environment.NewLine);
                                }
                            }
                        }
                        if (Enter)
                        {
                            tbRecebidoH.AppendText(sb.ToString());
                        }
                        else
                        {
                            //tbRecebidoH.Text += sb.ToString() + Environment.NewLine; //Acrescenta string e linha
                            tbRecebidoH.AppendText(sb.ToString() + Environment.NewLine); //Acrescenta string, linha e faz scroll automático
                        }
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder(c.Length * 2);//dois cracteres
                        foreach (byte b in c)
                        {
                            sb.AppendFormat("{0:x2}", b);
                            if (cbEnter.Checked)
                            {
                                if ((b == 0x0D) || (b == 0x0A))
                                {
                                    sb.Append(Environment.NewLine);
                                }
                            }
                        }
                        if (Enter)
                        {
                            tbRecebidoH.AppendText(sb.ToString());
                        }
                        else
                        {
                            //tbRecebidoH.Text += sb.ToString() + Environment.NewLine; //Acrescenta string e linha
                            tbRecebidoH.AppendText(sb.ToString() + Environment.NewLine); //Acrescenta string, linha e faz scroll automático
                        }
                    }

                    if (cbSom.Checked == true)
                    {
                        SystemSounds.Asterisk.Play();
                    }

                    //Sem tratamento dos códigos 0x0D e 0x0A (Enter)
                    ////Para mostrar em string
                    ////this.tbRecebido.Text += t + Environment.NewLine;  //Acrescenta string e linha
                    //this.tbRecebido.AppendText(t + Environment.NewLine);    //Acrescenta string, linha e faz scroll automático

                    ////Para mostrar em hexa
                    //if (cbHexaEspaço.Checked)
                    //{
                    //    StringBuilder sb = new StringBuilder(t.Length * 3);//dois cracteres + um espaço
                    //    foreach (byte b in t)
                    //    {
                    //        sb.AppendFormat("{0:x2} ", b);
                    //    }
                    //    //tbRecebidoH.Text += sb.ToString() + Environment.NewLine;    //Acrescenta string e linha
                    //    tbRecebidoH.AppendText(sb.ToString() + Environment.NewLine);    //Acrescenta string, linha e faz scroll automático
                    //}
                    //else
                    //{
                    //    StringBuilder sb = new StringBuilder(t.Length * 2);//dois cracteres
                    //    foreach (byte b in t)
                    //    {
                    //        sb.AppendFormat("{0:x2}", b);
                    //    }
                    //    //tbRecebidoH.Text += sb.ToString() + Environment.NewLine;    //Acrescenta string e linha
                    //    tbRecebidoH.AppendText(sb.ToString() + Environment.NewLine);    //Acrescenta string, linha e faz scroll automático
                    //}
                }
            }
            catch
            { }
        }