elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Hacer compatible C++ códigos de C#.
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Hacer compatible C++ códigos de C#.  (Leído 4,633 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Hacer compatible C++ códigos de C#.
« en: 23 Febrero 2015, 23:17 pm »

Hola:
Tengo este código dentro de un button para enviar tramas de bytes hecho con C#.

Código
  1. // Enviar tramas de bytes.
  2.  
  3.            byte[] miBuffer = new byte[9]; // Led_13_ON son 9 byte máximo.
  4.            miBuffer[0] = 0x4C; // ASCII letra "L".
  5.            miBuffer[1] = 0x65; // ASCII letra "e".
  6.            miBuffer[2] = 0x64; // ASCII letra "d".
  7.            miBuffer[3] = 0x5F; // ASCII letra "_".
  8.            miBuffer[4] = 0x31; // ASCII letra "1".
  9.            miBuffer[5] = 0x33; // ASCII letra "3".
  10.            miBuffer[6] = 0x5F; // ASCII letra "_".
  11.            miBuffer[7] = 0x4F; // ASCII letra "O".
  12.            miBuffer[8] = 0x4E; // ASCII letra "N".
  13.            serialPort1.Write(miBuffer, 0, miBuffer.Length); // Envia las tramas de bytes.

Da igual cuantras tramas hay que enviar, en C++ se hace así com indica abajo enviando la letra t.

Código
  1. cli::array<unsigned char> ^uno = gcnew cli::array<unsigned char> (1);
  2. uno[0] = 0x74; // ASCII letra "t".
  3. serialPort1->Write(uno, 0, 1);

Quiero hacer una cadena escrito más cómodamente como el ejemplo en C# hecho abajo.

Código
  1.            byte[] mBuffer = Encoding.ASCII.GetBytes("Led_8_ON");
  2.            serialPort1.Write(mBuffer, 0, mBuffer.Length);

¿Cómo se hace en Visual C++ 2010?

Gracias.


En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Hacer compatible C++ códigos de C#.
« Respuesta #1 en: 24 Febrero 2015, 01:51 am »

Hola:

Intenté ahcerlo así:
Código
  1. cli::array<unsigned char> ^mBuffer = Encoding::ASCII->GetBytes("Led_8_ON");
  2. serialPort1->Write(mBuffer, 0, mBuffer->Length);

Me da errores.


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: Hacer compatible C++ códigos de C#.
« Respuesta #2 en: 24 Febrero 2015, 03:05 am »

Me da errores.
¿Vas a mostrar y comentar el mensaje de error de compilación, o debemos adivinarlo?.  :¬¬



Practicamente no manejo nada en absoluto VC++, pero dispongo de una herramienta traductora privada que es bastante fiable, prueba utilizando esta sintaxis:
Código
  1. array<Byte> ^mBuffer = Encoding::ASCII->GetBytes("Led_8_ON");
  2. serialPort1::Write(mBuffer, 0, mBuffer->Length);

Saludos!
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Hacer compatible C++ códigos de C#.
« Respuesta #3 en: 24 Febrero 2015, 08:37 am »

Hola:

Tienes razón. Aquí están los errores que he me salió.
Citar
------ Operación Generar iniciada: proyecto: InterDuinoCPP, configuración: Debug Win32 ------
  InterDuinoCPP.cpp
c:\users\meta\documents\visual studio 2010\projects\interduinocpp\interduinocpp\Form1.h(195): error C2653: 'Enconding' : no es un nombre de clase o espacio de nombres
c:\users\meta\documents\visual studio 2010\projects\interduinocpp\interduinocpp\Form1.h(195): error C2065: 'ASCII' : identificador no declarado
c:\users\meta\documents\visual studio 2010\projects\interduinocpp\interduinocpp\Form1.h(195): error C2227: el operando izquierdo de '->GetBytes' debe señalar al tipo class/struct/union/generic
          el tipo es ''unknown-type''
c:\users\meta\documents\visual studio 2010\projects\interduinocpp\interduinocpp\Form1.h(196): error C2664: 'void System::IO::Ports::SerialPort::Write(System::String ^)' : no se puede convertir el parámetro 1 de 'int' a 'System::String ^'
          No hay un operador de conversión definida por el usuario disponible, o
          No existe una conversión estándar del formulario al que se le aplica la conversión boxing del tipo aritmético al tipo de destino
========== Generar: 0 correctos, 1 incorrectos, 0 actualizados, 0 omitidos ==========

En cuanto a tu código, da más errores y los mismos que estos del ASCII, Encoding.

Saludos y gracias por el intento.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.809



Ver Perfil
Re: Hacer compatible C++ códigos de C#.
« Respuesta #4 en: 24 Febrero 2015, 11:31 am »

El primer, el segundo, y el tercer error, suceden por que no se encuentra el namespace (como te está indicando). Importa el namespace donde se haya el miembro "Encoding" (System.Text.Encoding)...

Código
  1. using namespace System;
  2. using namespace System::Text;

El último error, se explica por si mismo también, el método SerialPort.Write no acepta el datatype Int como primer parámetro, sino un array de Byte, de Char, o un String. Cómo explica la MSDN:
https://msdn.microsoft.com/en-us/library/ms143551%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-1
El método por defecto acepta un String, y al no poder convertir un Int a String... pum.

Me imagino que al corregir los tres primeros errores de compilación referente al namespace y así poder asignar el array de bytes, se auto-corregirá el error de parametización del método serialport1.write() al mismo tiempo, puesto que estás intentando utilizar el overload que acepta un array de bytes.


PD: ¿Ves que pronto se solucionan más o menos las cosas cuando uno especifica la información necesaria al formular una pregunta de programación sobre un error?, que no eres nuevo en el foro, deberías saber ya lo molesto que resulta eso.

Saludos!
« Última modificación: 24 Febrero 2015, 11:40 am por Eleкtro » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Hacer compatible C++ códigos de C#.
« Respuesta #5 en: 24 Febrero 2015, 14:45 pm »

Hola Señor:

Aquí en español.
https://msdn.microsoft.com/es-es/library/ms143551%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=cpp&f=255&MSPPError=-2147217396#code-snippet-1

Aquí sobre Encoding y ASCCIEncoding, he puesto estos dos uses y nada.
https://msdn.microsoft.com/es-es/library/system.text.asciiencoding%28v=vs.110%29.aspx

A pesar que parece que es así:
[HIGHLIGHT="C++"]    cli::array<unsigned char> ^mBuffer = Encoding::ASCII->GetBytes("Led_8_ON");
    serialPort1->Write(mBuffer, 0, mBuffer->Length);[/HIGHLIGHT]

No lo es, todavía con los mismos errores que salen.

Lo que he hecho.


Paso 2.


Paso 3.



Paso 4.


Haces doble clic enun button y poner el código.

Este código C# quiero traducirlo a Visual C++ 2010.
Código:
private void button_b_Click(object sender, EventArgs e)
{
    byte[] mBuffer = Encoding.ASCII.GetBytes("Hello World");
    serialPort1.Write(mBuffer, 0, mBuffer.Length);
}

Saludos.
« Última modificación: 24 Febrero 2015, 16:42 pm por Meta » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Hacer compatible C++ códigos de C#.
« Respuesta #6 en: 25 Febrero 2015, 04:42 am »

Me ha servido enviar tramas, ahora toca recibir.

Código
  1. #pragma once
  2.  
  3. namespace Project1 {
  4.  
  5. using namespace System;
  6. using namespace System::ComponentModel;
  7. using namespace System::Collections;
  8. using namespace System::Windows::Forms;
  9. using namespace System::Data;
  10. using namespace System::Drawing;
  11.  
  12. using namespace System::IO::Ports; // No olvidar.
  13. using namespace System::Text;
  14.  
  15. /// <summary>
  16. /// Resumen de MyForm
  17. /// </summary>
  18. public ref class MyForm : public System::Windows::Forms::Form
  19. {
  20. // Utilizaremos un string como buffer de recepción.
  21. String^ Recibidos;
  22.  
  23. public:
  24. MyForm(void)
  25. {
  26. InitializeComponent();
  27. //
  28. //TODO: agregar código de constructor aquí
  29. //
  30. if (!serialPort1->IsOpen)
  31. {
  32. try
  33. {
  34. serialPort1->Open();
  35. }
  36. catch (Exception^ex)
  37. {
  38. MessageBox::Show(ex->ToString());
  39. }
  40. // Ejecutar la función Recepcion por disparo del Evento 'DataReived'.
  41. serialPort1->DataReceived += gcnew SerialDataReceivedEventHandler(Recepcion);
  42. }
  43. }
  44.  
  45. // Al recibir datos.
  46. private: void Recepcion(Object^ sender, SerialDataReceivedEventArgs^ e)
  47. {
  48. // Acumula los caracteres recibidos a nuestro 'buffer' (sting).
  49. Recibidos += serialPort1->ReadExisting();
  50.  
  51. // Invocar o llamar al proceso de tramas.
  52. Invoke(gcnew EventHandler(Actualizar));
  53. }
  54.  
  55. // Procesar los datos recibidos en el buffer y estraer tramas completas.
  56. private: void Actualizar(Object^ sender, EventArgs^ e)
  57. {
  58. // Asignar el valor de la trama al richTextBox.
  59. richTextBox_Mensajes->Text = Recibidos;
  60.  
  61. // Selecciona la posición final para leer los mensajes entrantes.
  62. richTextBox_Mensajes->SelectionStart = richTextBox_Mensajes->Text->Length;
  63.  
  64. // Mantiene el scroll en la entrada de cada mensaje.
  65. richTextBox_Mensajes->ScrollToCaret();
  66. }
  67.  
  68. protected:
  69. /// <summary>
  70. /// Limpiar los recursos que se estén utilizando.
  71. /// </summary>
  72. ~MyForm()
  73. {
  74. if (components)
  75. {
  76. delete components;
  77. }
  78. }
  79. private: System::Windows::Forms::Button^  button_Led_8_ON;
  80. protected:
  81. private: System::Windows::Forms::Button^  button_Led_8_OFF;
  82. private: System::IO::Ports::SerialPort^  serialPort1;
  83. private: System::Windows::Forms::RichTextBox^  richTextBox_Mensajes;
  84. private: System::ComponentModel::IContainer^  components;
  85.  
  86. protected:
  87.  
  88. private:
  89. /// <summary>
  90. /// Variable del diseñador requerida.
  91. /// </summary>
  92.  
  93.  
  94. #pragma region Windows Form Designer generated code
  95. /// <summary>
  96. /// Método necesario para admitir el Diseñador. No se puede modificar
  97. /// el contenido del método con el editor de código.
  98. /// </summary>
  99. void InitializeComponent(void)
  100. {
  101. this->components = (gcnew System::ComponentModel::Container());
  102. this->button_Led_8_ON = (gcnew System::Windows::Forms::Button());
  103. this->button_Led_8_OFF = (gcnew System::Windows::Forms::Button());
  104. this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this->components));
  105. this->richTextBox_Mensajes = (gcnew System::Windows::Forms::RichTextBox());
  106. this->SuspendLayout();
  107. //
  108. // button_Led_8_ON
  109. //
  110. this->button_Led_8_ON->Location = System::Drawing::Point(33, 39);
  111. this->button_Led_8_ON->Name = L"button_Led_8_ON";
  112. this->button_Led_8_ON->Size = System::Drawing::Size(75, 23);
  113. this->button_Led_8_ON->TabIndex = 0;
  114. this->button_Led_8_ON->Text = L"ON";
  115. this->button_Led_8_ON->UseVisualStyleBackColor = true;
  116. this->button_Led_8_ON->Click += gcnew System::EventHandler(this, &MyForm::button_Led_8_ON_Click);
  117. //
  118. // button_Led_8_OFF
  119. //
  120. this->button_Led_8_OFF->Location = System::Drawing::Point(33, 81);
  121. this->button_Led_8_OFF->Name = L"button_Led_8_OFF";
  122. this->button_Led_8_OFF->Size = System::Drawing::Size(75, 23);
  123. this->button_Led_8_OFF->TabIndex = 1;
  124. this->button_Led_8_OFF->Text = L"OFF";
  125. this->button_Led_8_OFF->UseVisualStyleBackColor = true;
  126. this->button_Led_8_OFF->Click += gcnew System::EventHandler(this, &MyForm::button_Led_8_OFF_Click);
  127. //
  128. // serialPort1
  129. //
  130. this->serialPort1->BaudRate = 115200;
  131. this->serialPort1->PortName = L"COM4";
  132. //
  133. // richTextBox_Mensajes
  134. //
  135. this->richTextBox_Mensajes->Dock = System::Windows::Forms::DockStyle::Bottom;
  136. this->richTextBox_Mensajes->Location = System::Drawing::Point(0, 137);
  137. this->richTextBox_Mensajes->Name = L"richTextBox_Mensajes";
  138. this->richTextBox_Mensajes->Size = System::Drawing::Size(284, 125);
  139. this->richTextBox_Mensajes->TabIndex = 2;
  140. this->richTextBox_Mensajes->Text = L"";
  141. //
  142. // MyForm
  143. //
  144. this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
  145. this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
  146. this->ClientSize = System::Drawing::Size(284, 262);
  147. this->Controls->Add(this->richTextBox_Mensajes);
  148. this->Controls->Add(this->button_Led_8_OFF);
  149. this->Controls->Add(this->button_Led_8_ON);
  150. this->Name = L"MyForm";
  151. this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
  152. this->Text = L"MyForm";
  153. this->ResumeLayout(false);
  154.  
  155. }
  156. #pragma endregion
  157. private: System::Void button_Led_8_ON_Click(System::Object^  sender, System::EventArgs^  e) {
  158. cli::array<unsigned char> ^miBuffer = gcnew cli::array<unsigned char>(9);
  159. miBuffer[0] = 0x4C; // ASCII letra "L".
  160. miBuffer[1] = 0x65; // ASCII letra "e".
  161. miBuffer[2] = 0x64; // ASCII letra "d".
  162. miBuffer[3] = 0x5F; // ASCII letra "_".
  163. miBuffer[4] = 0x31; // ASCII letra "1".
  164. miBuffer[5] = 0x33; // ASCII letra "3".
  165. miBuffer[6] = 0x5F; // ASCII letra "_".
  166. miBuffer[7] = 0x4F; // ASCII letra "O".
  167. miBuffer[8] = 0x4E; // ASCII letra "N".
  168. serialPort1->Write(miBuffer, 0, miBuffer->Length);
  169. }
  170. private: System::Void button_Led_8_OFF_Click(System::Object^  sender, System::EventArgs^  e) {
  171. array<Byte> ^miBuffer = Encoding::ASCII->GetBytes("Led_13_OFF");
  172. serialPort1->Write(miBuffer, 0, miBuffer->Length);
  173. }
  174. };
  175. }
  176.  

Me dan estos errores y creo que es por mala traducción.
Citar
Error   2   error C3350: 'System::IO::Ports::SerialDataReceivedEventHandler' : un constructor de delegado espera 2 argumentos   c:\users\meta\documents\visual studio 2013\projects\project1\project1\MyForm.h   41   1   Project1

Otro error.
Citar
Error   3   error C3867: 'Project1::MyForm::Actualizar': falta la lista de argumentos de la llamada a la función; utilice '&Project1::MyForm::Actualizar' para crear un puntero al miembro   c:\users\meta\documents\visual studio 2013\projects\project1\project1\MyForm.h   52   1   Project1
« Última modificación: 25 Febrero 2015, 06:48 am por Meta » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Hacer compatible C++ códigos de C#.
« Respuesta #7 en: 26 Febrero 2015, 00:19 am »

Ya encontré la solución y funciona.

Se los dejo aquí por si alguien le hace falta o le pueda interesar.

Código
  1. #pragma once
  2.  
  3. namespace InterDuinoCPP {
  4.  
  5. using namespace System;
  6. using namespace System::ComponentModel;
  7. using namespace System::Collections;
  8. using namespace System::Windows::Forms;
  9. using namespace System::Data;
  10. using namespace System::Drawing;
  11.  
  12. using namespace System::IO::Ports; // No olvidar.
  13. using namespace System::Text;
  14.  
  15. /// <summary>
  16. /// Resumen de Form_Principal
  17. /// </summary>
  18. public ref class Form_Principal : public System::Windows::Forms::Form
  19. {
  20. public:
  21. Form_Principal(void)
  22. {
  23. InitializeComponent();
  24. //
  25. //TODO: agregar código de constructor aquí
  26. //
  27.  
  28. // Abrir puerto miestras se ejecuta la aplicación.
  29. if (!serialPort1->IsOpen)
  30. {
  31. try
  32. {
  33. serialPort1->Open();
  34. }
  35. catch (Exception^ex)
  36. {
  37. MessageBox::Show(ex->ToString());
  38. }
  39. }
  40. }
  41.  
  42. protected:
  43. /// <summary>
  44. /// Limpiar los recursos que se estén utilizando.
  45. /// </summary>
  46. ~Form_Principal()
  47. {
  48. if (components)
  49. {
  50. delete components;
  51. }
  52. }
  53. private: System::Windows::Forms::Button^  button_Led_8_ON;
  54. private: System::Windows::Forms::Button^  button_Led_8_OFF;
  55. protected:
  56.  
  57. protected:
  58.  
  59. private: System::Windows::Forms::Label^  label1;
  60. private: System::Windows::Forms::Button^  button_Led_13_ON;
  61. private: System::Windows::Forms::Button^  button_Led_13_OFF;
  62.  
  63.  
  64. private: System::Windows::Forms::Label^  label2;
  65. private: System::Windows::Forms::RichTextBox^  richTextBox_Mensajes;
  66.  
  67. private: System::Windows::Forms::Label^  label3;
  68. private: System::IO::Ports::SerialPort^  serialPort1;
  69. private: System::ComponentModel::IContainer^  components;
  70.  
  71. private:
  72. /// <summary>
  73. /// Variable del diseñador requerida.
  74. /// </summary>
  75.  
  76.  
  77. #pragma region Windows Form Designer generated code
  78. /// <summary>
  79. /// Método necesario para admitir el Diseñador. No se puede modificar
  80. /// el contenido del método con el editor de código.
  81. /// </summary>
  82. void InitializeComponent(void)
  83. {
  84. this->components = (gcnew System::ComponentModel::Container());
  85. this->button_Led_8_ON = (gcnew System::Windows::Forms::Button());
  86. this->button_Led_8_OFF = (gcnew System::Windows::Forms::Button());
  87. this->label1 = (gcnew System::Windows::Forms::Label());
  88. this->button_Led_13_ON = (gcnew System::Windows::Forms::Button());
  89. this->button_Led_13_OFF = (gcnew System::Windows::Forms::Button());
  90. this->label2 = (gcnew System::Windows::Forms::Label());
  91. this->richTextBox_Mensajes = (gcnew System::Windows::Forms::RichTextBox());
  92. this->label3 = (gcnew System::Windows::Forms::Label());
  93. this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this->components));
  94. this->SuspendLayout();
  95. //
  96. // button_Led_8_ON
  97. //
  98. this->button_Led_8_ON->Location = System::Drawing::Point(43, 37);
  99. this->button_Led_8_ON->Name = L"button_Led_8_ON";
  100. this->button_Led_8_ON->Size = System::Drawing::Size(75, 23);
  101. this->button_Led_8_ON->TabIndex = 0;
  102. this->button_Led_8_ON->Text = L"ON";
  103. this->button_Led_8_ON->UseVisualStyleBackColor = true;
  104. this->button_Led_8_ON->Click += gcnew System::EventHandler(this, &Form_Principal::button_Led_8_ON_Click);
  105. //
  106. // button_Led_8_OFF
  107. //
  108. this->button_Led_8_OFF->Location = System::Drawing::Point(43, 77);
  109. this->button_Led_8_OFF->Name = L"button_Led_8_OFF";
  110. this->button_Led_8_OFF->Size = System::Drawing::Size(75, 23);
  111. this->button_Led_8_OFF->TabIndex = 1;
  112. this->button_Led_8_OFF->Text = L"OFF";
  113. this->button_Led_8_OFF->UseVisualStyleBackColor = true;
  114. this->button_Led_8_OFF->Click += gcnew System::EventHandler(this, &Form_Principal::button_Led_8_OFF_Click);
  115. //
  116. // label1
  117. //
  118. this->label1->AutoSize = true;
  119. this->label1->Location = System::Drawing::Point(62, 21);
  120. this->label1->Name = L"label1";
  121. this->label1->Size = System::Drawing::Size(34, 13);
  122. this->label1->TabIndex = 2;
  123. this->label1->Text = L"Led 8";
  124. //
  125. // button_Led_13_ON
  126. //
  127. this->button_Led_13_ON->Location = System::Drawing::Point(166, 37);
  128. this->button_Led_13_ON->Name = L"button_Led_13_ON";
  129. this->button_Led_13_ON->Size = System::Drawing::Size(75, 23);
  130. this->button_Led_13_ON->TabIndex = 3;
  131. this->button_Led_13_ON->Text = L"ON";
  132. this->button_Led_13_ON->UseVisualStyleBackColor = true;
  133. this->button_Led_13_ON->Click += gcnew System::EventHandler(this, &Form_Principal::button_Led_13_ON_Click);
  134. //
  135. // button_Led_13_OFF
  136. //
  137. this->button_Led_13_OFF->Location = System::Drawing::Point(166, 77);
  138. this->button_Led_13_OFF->Name = L"button_Led_13_OFF";
  139. this->button_Led_13_OFF->Size = System::Drawing::Size(75, 23);
  140. this->button_Led_13_OFF->TabIndex = 4;
  141. this->button_Led_13_OFF->Text = L"OFF";
  142. this->button_Led_13_OFF->UseVisualStyleBackColor = true;
  143. this->button_Led_13_OFF->Click += gcnew System::EventHandler(this, &Form_Principal::button_Led_13_OFF_Click);
  144. //
  145. // label2
  146. //
  147. this->label2->AutoSize = true;
  148. this->label2->Location = System::Drawing::Point(186, 21);
  149. this->label2->Name = L"label2";
  150. this->label2->Size = System::Drawing::Size(40, 13);
  151. this->label2->TabIndex = 5;
  152. this->label2->Text = L"Led 13";
  153. //
  154. // richTextBox_Mensajes
  155. //
  156. this->richTextBox_Mensajes->Dock = System::Windows::Forms::DockStyle::Bottom;
  157. this->richTextBox_Mensajes->Location = System::Drawing::Point(0, 129);
  158. this->richTextBox_Mensajes->Name = L"richTextBox_Mensajes";
  159. this->richTextBox_Mensajes->Size = System::Drawing::Size(284, 133);
  160. this->richTextBox_Mensajes->TabIndex = 6;
  161. this->richTextBox_Mensajes->Text = L"";
  162. //
  163. // label3
  164. //
  165. this->label3->AutoSize = true;
  166. this->label3->Location = System::Drawing::Point(12, 113);
  167. this->label3->Name = L"label3";
  168. this->label3->Size = System::Drawing::Size(121, 13);
  169. this->label3->TabIndex = 7;
  170. this->label3->Text = L"Mensaje desde Arduino:";
  171. //
  172. // serialPort1
  173. //
  174. this->serialPort1->BaudRate = 115200;
  175. this->serialPort1->PortName = L"COM4";
  176. this->serialPort1->DataReceived += gcnew System::IO::Ports::SerialDataReceivedEventHandler(this, &Form_Principal::serialPort1_DataReceived);
  177. //
  178. // Form_Principal
  179. //
  180. this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
  181. this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
  182. this->ClientSize = System::Drawing::Size(284, 262);
  183. this->Controls->Add(this->label3);
  184. this->Controls->Add(this->richTextBox_Mensajes);
  185. this->Controls->Add(this->label2);
  186. this->Controls->Add(this->button_Led_13_OFF);
  187. this->Controls->Add(this->button_Led_13_ON);
  188. this->Controls->Add(this->label1);
  189. this->Controls->Add(this->button_Led_8_OFF);
  190. this->Controls->Add(this->button_Led_8_ON);
  191. this->Name = L"Form_Principal";
  192. this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
  193. this->Text = L"Mini Interfaz C++";
  194. this->ResumeLayout(false);
  195. this->PerformLayout();
  196.  
  197. }
  198. #pragma endregion
  199. private: System::Void button_Led_8_ON_Click(System::Object^  sender, System::EventArgs^  e) {
  200. array<Byte> ^miBuffer = Encoding::ASCII->GetBytes("Led_8_ON");
  201. serialPort1->Write(miBuffer, 0, miBuffer->Length);
  202. }
  203. private: System::Void button_Led_8_OFF_Click(System::Object^  sender, System::EventArgs^  e) {
  204. array<Byte> ^miBuffer = Encoding::ASCII->GetBytes("Led_8_OFF");
  205. serialPort1->Write(miBuffer, 0, miBuffer->Length);
  206. }
  207.  
  208. private: System::Void button_Led_13_ON_Click(System::Object^  sender, System::EventArgs^  e) {
  209. cli::array<unsigned char> ^miBuffer = gcnew cli::array<unsigned char>(9);
  210. miBuffer[0] = 0x4C; // ASCII letra "L".
  211. miBuffer[1] = 0x65; // ASCII letra "e".
  212. miBuffer[2] = 0x64; // ASCII letra "d".
  213. miBuffer[3] = 0x5F; // ASCII letra "_".
  214. miBuffer[4] = 0x31; // ASCII letra "1".
  215. miBuffer[5] = 0x33; // ASCII letra "3".
  216. miBuffer[6] = 0x5F; // ASCII letra "_".
  217. miBuffer[7] = 0x4F; // ASCII letra "O".
  218. miBuffer[8] = 0x4E; // ASCII letra "N".
  219. serialPort1->Write(miBuffer, 0, miBuffer->Length);
  220. }
  221.  
  222. private: System::Void button_Led_13_OFF_Click(System::Object^  sender, System::EventArgs^  e) {
  223. cli::array<unsigned char> ^miBuffer = gcnew cli::array<unsigned char>(10);
  224. miBuffer[0] = 0x4C; // ASCII letra "L".
  225. miBuffer[1] = 0x65; // ASCII letra "e".
  226. miBuffer[2] = 0x64; // ASCII letra "d".
  227. miBuffer[3] = 0x5F; // ASCII letra "_".
  228. miBuffer[4] = 0x31; // ASCII letra "1".
  229. miBuffer[5] = 0x33; // ASCII letra "3".
  230. miBuffer[6] = 0x5F; // ASCII letra "_".
  231. miBuffer[7] = 0x4F; // ASCII letra "O".
  232. miBuffer[8] = 0x46; // ASCII letra "F".
  233. miBuffer[9] = 0x46; // ASCII letra "F".
  234. serialPort1->Write(miBuffer, 0, miBuffer->Length);
  235. }
  236.  
  237. // Declaramos un delegado.
  238. delegate void Delegado(String ^ Recibidos);
  239.  
  240. private: Void serialPort1_DataReceived(Object^  sender, SerialDataReceivedEventArgs^  e) {
  241. // Utilizremos un string como buffer de recepción.
  242. String ^ Recibidos;
  243.  
  244. if (serialPort1->BytesToRead > 0){ // Si hay carácter que leer...
  245.  
  246. Recibidos = serialPort1->ReadExisting(); // Acumula los carácteres recibido.
  247.  
  248. // Invocamos y cargamos los bytes en rictTextBox_Mensajes.
  249. Delegado ^ Actualizar = gcnew Delegado(this, &Form_Principal::ByteRecibidos);
  250.  
  251. this->Invoke(Actualizar, Recibidos);
  252. }
  253. }
  254.  
  255. void ByteRecibidos(String ^ Data){
  256. // Los carácteres almacenado en 'Data' se depositan en richTextBox_Mensaje.
  257. richTextBox_Mensajes->Text += Data;
  258.  
  259. // Selecciona la posición final para leer los mensajes entrantes.
  260. richTextBox_Mensajes->SelectionStart = richTextBox_Mensajes->Text->Length;
  261.  
  262. // Mantiene el scroll en la entrada de cada mensaje.
  263. richTextBox_Mensajes->ScrollToCaret();
  264. }
  265.  
  266. };
  267. }

Saludos.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
como hacer compatible flat out 2 en windows 7?
Juegos y Consolas
troyano_carlos 0 2,821 Último mensaje 4 Abril 2012, 16:53 pm
por troyano_carlos
Hacer código compatible y legible.
Electrónica
Meta 0 2,405 Último mensaje 10 Febrero 2015, 18:21 pm
por Meta
Notebook compatible para hacer sniffing en Debian?
GNU/Linux
WHK 3 2,114 Último mensaje 3 Diciembre 2015, 18:15 pm
por WHK
Hacer un inyector compatible con 32 y 64 bits
Programación General
Borito30 0 1,740 Último mensaje 28 Noviembre 2016, 00:18 am
por Borito30
Como hacer un respaldo de sql2008r2 compatible con sql2005
Bases de Datos
Lecoq01 2 1,888 Último mensaje 8 Abril 2019, 05:21 am
por Lecoq01
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines