151
Programación / .NET (C#, VB.NET, ASP) / ¿Por qué me salen botones repetidos?
en: 19 Noviembre 2017, 09:24 am
Hola:
Tengo esta ventana creada con PowerShell. Lo que no entiendo por mucho que observe el código, es que me aparezcan dos botones iguales en la parte de arriba.
# Cargo los Assemblies (necesario para definir el form). [void][reflection.assembly]::loadwithpartialname("System.Windows.Forms") [void][reflection.assembly]::loadwithpartialname("System.Drawing") $label_Mensaje = New-Object System.Windows.Forms.Label $button_Abrir = New-Object System.Windows.Forms.Button $button_Cerrar = New-Object System.Windows.Forms.Button $groupBox_Bandeja = New-Object System.Windows.Forms.GroupBox # # label_Mensaje # $label_Mensaje.Location = New-Object System.Drawing.Point(12, 9) $label_Mensaje.Name = "label_Mensaje" $label_Mensaje.Size = New-Object System.Drawing.Size(58, 13) $label_Mensaje.Text = "Abriendo..." # # button_Abrir # $button_Abrir.Location = New-Object System.Drawing.Point(31, 30) $button_Abrir.Name = "button_Abrir" $button_Abrir.Size = New-Object System.Drawing.Size(75, 23) $button_Abrir.Text = "Abrir" # # button_Cerrar # $button_Cerrar.Location = New-Object System.Drawing.Point(139, 30) $button_Cerrar.Name = "button_Cerrar" $button_Cerrar.Size = New-Object System.Drawing.Size(75, 23) $button_Cerrar.Text = "Cerrar" # # groupBox_Bandeja # $groupBox_Bandeja.Controls.Add($button_Cerrar) $groupBox_Bandeja.Controls.Add($button_Abrir) $groupBox_Bandeja.Location = New-Object System.Drawing.Point(15, 118) $groupBox_Bandeja.Name = "groupBox_Bandeja" $groupBox_Bandeja.Size = New-Object System.Drawing.Size(250, 97) $groupBox_Bandeja.Text = "Bandeja" # # Form1 # #$AutoScaleDimensions = New-Object System.Drawing.SizeF(6F, 13F) #$AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font $Form.ClientSize = New-Object System.Drawing.Size(284, 261) $Form.Controls.Add($groupBox_Bandeja) $Form.Controls.Add($label_Mensaje) $Form.Name = "Form1" $Form.Text = "Ventana PowerShell" # Ejecuto el formulario. [void]$Form.ShowDialog() Saludos.
152
Programación / Scripting / Hacer un menú sencillo con este Script
en: 19 Noviembre 2017, 07:22 am
Hola a todos y a todas:
Quiero hacer un menú sencillo que las funciones se hará después.
Por ahora he hecho esto de esta manera haciendo pruebas.
╔====================================╗ ║ Control bandeja del lector ║ ╠====================================╣ ║ ║ 1) Primera Opción 2) Segunda Opción 3) Tercera Opción S) Presiona 'S' para salir Elegir una Opción:
Como puedes ver, pulso el número 2), luego Enter para poder entrar en el menú. Mi idea es, desde que pulses la tecla número 2), entre directamente a la Segunda opción sin tener que pulsar Enter.
{ param ( [string]$Titulo = ' Control bandeja del lector ' ) cls Write-Host "╔====================================╗" Write-Host "║ $Titulo ║" Write-Host "╠====================================╣" Write-Host "║ ║" Write-Host "1) Primera Opción" Write-Host "2) Segunda Opción" Write-Host "3) Tercera Opción" Write-Host "S) Presiona 'S' para salir" } do { mostrarMenu $input = Read-Host "Elegir una Opción" switch ($input) { '1' { cls 'Primera Opción' } '2' { cls 'Segunda Opción' } '3' { cls 'Tercera Opción' } 's' { return } } pause } until ($input -eq 's') ¿Cómo se hace lo que quiero?
Saludos.
153
Programación / Programación C/C++ / [SOLUCIONADO] Solucionando errores Menú abrir y cerrar unidad CD-ROM
en: 18 Noviembre 2017, 21:06 pm
Hola:
He hecho este programa para poder abrir y cerrar la bandeja con C++ Win32. Lo que tiene que hacer es si pulsa la tecla A, se abre el lector, si pulsas C, cierra la bandeja del lector de discos.
#include "stdafx.h"
#include "stdio.h"
#include "Windows.h"
#include "iostream"
#include "string"
#include "conio.h"
using namespace std;
int main( )
{
// Título de la ventana.
SetConsoleTitle( L"Abrir y cerrar bandeja del disco C++ Win32" ) ;
// Variable
char entrada[ ] = "\0 " ; // Guarda A, a, C, y c tipo string que introduces desde la consola.
while ( true )
{
printf ( "Control bandeja del lector : \n \n " ) ;
printf ( "A - Abrir bandeja. \n " ) ;
printf ( "C - Cerrar bandeja. \n " ) ;
printf ( "========================== \n \n " ) ;
cin >> entrada; // Aquí introduces letras A, a, C, y c.
switch ( srt.tolower ( entrada) ) // Espera recibir A, a, C, y c. Transforma en minúscula.
{
// Abrir bandeja.
case 'a' :
cout << "Abriendo..." << endl; // Muestra en pantalla textos.
//printf("Abriendo...");
// Aquí va un evento para que aparezca la palabra Abirendo... mientra se está abriendo el lector.
mciSendString( L"set cdaudio door open" , nullptr, 0 , nullptr) ;
cout << "Abierto." << endl; // Muestra en pantalla textos.
break ;
// Cerrar bandeja.
case 'b' :
cout << "Cerrando..." << endl; // Muestra en pantalla textos.
// Aquí va un evento.
mciSendString( L"set cdaudio door closed" , nullptr, 0 , nullptr) ;
cout << "Cerrado." << endl; // Muestra en pantalla textos.
break ;
default : // Si haz pulsado otro caracter distinto de A, C, a, y c aparece
cout << "Solo pulsar A o C." << endl; // este mensaje.
}
}
return EXIT_SUCCESS ;
}
¿Qué tengo mal?
Saludos.
154
Programación / Programación General / [SOLUCIONADO] Han cambiado las cosa al actualizar Visual Studio Community 2017
en: 18 Noviembre 2017, 08:27 am
Hola:
Trabajando con MFC al crear formularios, me salía esta ventana al final en el cual podía ejecutar al pulsar F5 para compilar.
Ver zoom .
Aquí abajo dejo una guía paso a paso de crear un formulario MFC como se hacía antes desde la
página 36, hasta la página 45 .
Ver visor .
Ver pdf .
Intenté seguir los pasos, la primera ventana me sale esto.
No se cual es la mejor forma de hacerlo. Lo dejo tal cual por si acaso y sigo a la página siguiente.
Sigo el siguiente paso.
Siguiente paso.
Siente paso.
Antes al ejecutar no me daba problemas. Ahora me salen todos estos errores indicado abajo y no se como solucionarlo.
¿Hay alguna solución?
Antes, podía ejecutar la ventana y no pasaba nada.
Saludos.
PD:
Disculpen si no me sale el tamaño adecuado de las capturas.
155
Programación / Programación C/C++ / Adaptar C++ CLR a C++ Win32
en: 16 Noviembre 2017, 12:15 pm
Hola:
Quiero adaptar este código de C++ CLR a C++ Win32. Antes que nada, quiero saber si es posible o hay que complicarse mucho la vida para hacer lo mismo. El código lo que hace es abrir y cerrar la bandeja de cualquier lector de discos sea IDE o SATA.
Aquí encontré un vídeo pero solo ejecuta, y abre el lector en Win32. Por algo se empieza.
VIDEO Código C++ CLR :#include "stdafx.h"
using namespace System;
using namespace System:: Runtime :: InteropServices ;
using namespace System:: Text ;
[ DllImport( "winmm.dll" ) ]
extern Int32 mciSendString( String^ lpstrCommand, StringBuilder^ lpstrReturnString,
int uReturnLength, IntPtr hwndCallback) ;
static void DoEvents( )
{
Console:: SetCursorPosition ( 0 , 6 ) ;
Console:: Write ( "Abriendo..." ) ;
}
static void DoEvents2( )
{
Console:: SetCursorPosition ( 0 , 6 ) ;
Console:: Write ( "Cerrando..." ) ;
}
int main( array< System:: String ^ > ^ args)
{
StringBuilder^ rt = gcnew StringBuilder( 127 ) ;
// Título de la ventana.
Console:: Title = "Control lector de bandeja. C++ CLR" ;
// Tamaño ventana consola.
Console:: WindowWidth = 29 ; // X. Ancho.
Console:: WindowHeight = 8 ; // Y. Alto.
// Cursor invisible.
Console:: CursorVisible = false ;
// Posición del mansaje en la ventana.
Console:: SetCursorPosition ( 0 , 0 ) ;
Console:: WriteLine ( "Control bandeja del lector : \n \n " +
"A - Abrir bandeja. \n " +
"C - Cerrar bandeja. \n " +
"========================== \n " ) ;
//Console::WriteLine("A - Abrir bandeja.");
//Console::WriteLine("C - Cerrar bandeja.");
//Console::Write("==========================");
ConsoleKey key;
//Console::CursorVisible = false;
do
{
key = Console:: ReadKey ( true ) .Key ;
String^ mensaje = "" ;
//Asignamos la tecla presionada por el usuario
switch ( key)
{
case ConsoleKey:: A :
mensaje = "Abriendo..." ;
Console:: SetCursorPosition ( 0 , 6 ) ;
DoEvents( ) ;
mciSendString( "set CDAudio door open" , rt, 127 , IntPtr:: Zero ) ;
mensaje = "Abierto." ;
break ;
case ConsoleKey:: C :
mensaje = "Cerrando..." ;
Console:: SetCursorPosition ( 0 , 6 ) ;
DoEvents2( ) ;
mciSendString( "set CDAudio door closed" , rt, 127 , IntPtr:: Zero ) ;
mensaje = "Cerrado." ;
break ;
}
Console:: SetCursorPosition ( 0 , 6 ) ;
Console:: Write ( " " ) ;
Console:: SetCursorPosition ( 0 , 6 ) ;
Console:: Write ( mensaje) ;
} while ( key ! = ConsoleKey:: Escape ) ;
return 0 ;
}
Saludos.
156
Programación / .NET (C#, VB.NET, ASP) / Hacer funcionar el lector de bandeja de discos con este lenguaje .net
en: 15 Noviembre 2017, 21:59 pm
Buenas a todos y a todas:
Quiero pasar este código en consola de C#, VB .net o el C++ CLR a F#. Lo que hace el código es si pulsas A o la letra C abre o cierra la bandeja del lector de discos. A parte de C#, también está en C++ CLR y VB .net por si lo entienden mejor. Lo que hace el código es abrir y cerrar la bandeja de discos del lector, sea IDE o SATA.
Código C# :using System; using System.Runtime.InteropServices; using System.Text; namespace Lector_teclado_consola_cs { class Program { [DllImport("winmm.dll")] public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback); public static StringBuilder rt = new StringBuilder(127); public static void DoEvents() { // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); Console.SetCursorPosition(0, 6); Console.Write("Abriendo..."); } public static void DoEvents2() { // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); Console.SetCursorPosition(0, 6); Console.Write("Cerrando..."); } static void Main(string[] args) { // Título de la ventana. Console.Title = "Control lector de bandeja. C#"; // Tamaño ventana consola. Console.WindowWidth = 29; // X. Ancho. Console.WindowHeight = 8; // Y. Alto. // Cursor invisible. Console.CursorVisible = false; // Posición del mansaje en la ventana. Console.SetCursorPosition(0, 0); Console.Write(@"Control bandeja del lector: A - Abrir bandeja. C - Cerrar bandeja. ==========================="); ConsoleKey key; //Console.CursorVisible = false; do { key = Console.ReadKey(true).Key; string mensaje = string.Empty; //Asignamos la tecla presionada por el usuario switch (key) { case ConsoleKey.A: // mensaje = "Abriendo..."; Console.SetCursorPosition(0, 6); DoEvents(); mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero); mensaje = "Abierto."; break; case ConsoleKey.C: // mensaje = "Cerrando..."; Console.SetCursorPosition(0, 6); DoEvents2(); mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero); mensaje = "Cerrado."; break; } Console.SetCursorPosition(0, 6); Console.Write(" "); Console.SetCursorPosition(0, 6); Console.Write(mensaje); } while (key != ConsoleKey.Escape); } } } Código VB .net :Imports System.Runtime.InteropServices Imports System.Text Module Module1 <DllImport("winmm.dll")> Public Function mciSendString(lpstrCommand As String, lpstrReturnString As StringBuilder, uReturnLength As Integer, hwndCallback As IntPtr) As Int32 End Function Public rt As New StringBuilder(127) Public Sub DoEvents() ' Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); Console.SetCursorPosition(0, 6) Console.Write("Abriendo...") End Sub Public Sub DoEvents2() ' Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); Console.SetCursorPosition(0, 6) Console.Write("Cerrando...") End Sub Sub Main() ' Título de la ventana. Console.Title = "Control lector de bandeja. Visual Basic" ' Tamaño ventana consola. Console.WindowWidth = 29 ' X. Ancho. Console.WindowHeight = 8 ' Y. Alto. ' Cursor invisible. Console.CursorVisible = False ' Posición del mansaje en la ventana. Console.SetCursorPosition(0, 0) Console.Write("Control bandeja del lector:" & vbCr & vbLf & vbCr & vbLf & "A - Abrir bandeja." & vbCr & vbLf & "C - Cerrar bandeja." & vbCr & vbLf & "===========================") Dim key As ConsoleKey 'Console.CursorVisible = false; Do key = Console.ReadKey(True).Key Dim mensaje As String = String.Empty 'Asignamos la tecla presionada por el usuario Select Case key Case ConsoleKey.A ' mensaje = "Abriendo..."; Console.SetCursorPosition(0, 6) DoEvents() mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero) mensaje = "Abierto." Exit Select Case ConsoleKey.C ' mensaje = "Cerrando..."; Console.SetCursorPosition(0, 6) DoEvents2() mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero) mensaje = "Cerrado." Exit Select End Select Console.SetCursorPosition(0, 6) Console.Write(" ") Console.SetCursorPosition(0, 6) Console.Write(mensaje) Loop While key <> ConsoleKey.Escape End Sub End Module Código C++ CLR :#include "stdafx.h" using namespace System; using namespace System::Runtime::InteropServices; using namespace System::Text; [DllImport("winmm.dll")] extern Int32 mciSendString(String^ lpstrCommand, StringBuilder^ lpstrReturnString, int uReturnLength, IntPtr hwndCallback); static void DoEvents() { Console::SetCursorPosition(0, 6); Console::Write("Abriendo..."); } static void DoEvents2() { Console::SetCursorPosition(0, 6); Console::Write("Cerrando..."); } int main(array<System::String ^> ^args) { StringBuilder^ rt = gcnew StringBuilder(127); // Título de la ventana. Console::Title = "Control lector de bandeja. C++ CLR"; // Tamaño ventana consola. Console::WindowWidth = 29; // X. Ancho. Console::WindowHeight = 8; // Y. Alto. // Cursor invisible. Console::CursorVisible = false; // Posición del mansaje en la ventana. Console::SetCursorPosition(0, 0); Console::WriteLine("Control bandeja del lector : \n\n" + "A - Abrir bandeja. \n" + "C - Cerrar bandeja. \n" + "========================== \n"); //Console::WriteLine("A - Abrir bandeja."); //Console::WriteLine("C - Cerrar bandeja."); //Console::Write("=========================="); ConsoleKey key; //Console::CursorVisible = false; do { key = Console::ReadKey(true).Key; String^ mensaje = ""; //Asignamos la tecla presionada por el usuario switch (key) { case ConsoleKey::A: mensaje = "Abriendo..."; Console::SetCursorPosition(0, 6); DoEvents(); mciSendString("set CDAudio door open", rt, 127, IntPtr::Zero); mensaje = "Abierto."; break; case ConsoleKey::C: mensaje = "Cerrando..."; Console::SetCursorPosition(0, 6); DoEvents2(); mciSendString("set CDAudio door closed", rt, 127, IntPtr::Zero); mensaje = "Cerrado."; break; } Console::SetCursorPosition(0, 6); Console::Write(" "); Console::SetCursorPosition(0, 6); Console::Write(mensaje); } while (key != ConsoleKey::Escape); return 0; } Del .net me falta F# y acabo esta curiosidad y retillo que tengo pendiente desde hace vete a saber.
¿Algún atrevido para poder abrir y cerrar la bandeja del lector usando el lenguaje F#?
Tienes que tener iniciativa para empezar y convencido para terminarlo.
Un cordial saludos a todos y a todas.
157
Programación / .NET (C#, VB.NET, ASP) / Detectar cuando la bandeja del lector está abierta o cerrada
en: 12 Noviembre 2017, 01:04 am
Hola:
Aquí hay un código que pulsando A o C abre o cierras la bandeja del lector, a parte de esto, dice Abierto, Abriendo... Cerrado y Cerrando... Todo esto pulsado las teclas A o C.
Me he dado cuenta que si cierro la bandeja directamente con la mano, en la ventana o en el CMD de C#, no lo sabe, se queda en Abierto. La idea es que si cierro la bandeja con la mano, en la pantalla muestre el mensaje.
¿Esto es posible de hacer?
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using static System.Net.Mime.MediaTypeNames; namespace Lector_teclado_consola_cs { class Program { [DllImport("winmm.dll")] public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback); public static StringBuilder rt = new StringBuilder(127); public static void DoEvents() { // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); Console.SetCursorPosition(0, 6); Console.Write("Abriendo..."); } public static void DoEvents2() { // Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); Console.SetCursorPosition(0, 6); Console.Write("Cerrando..."); } static void Main(string[] args) { // Título de la ventana. Console.Title = "Control lector de bandeja."; // Tamaño ventana consola. Console.WindowWidth = 55; // X. Ancho. Console.WindowHeight = 18; // Y. Alto. // Cursor invisible. Console.CursorVisible = false; // Posición del mansaje en la ventana. Console.SetCursorPosition(0, 0); Console.Write(@"Control bandeja del lector: A - Abrir bandeja. C - Cerrar bandeja. ==========================="); ConsoleKey key; //Console.CursorVisible = false; do { key = Console.ReadKey(true).Key; string mensaje = string.Empty; //Asignamos la tecla presionada por el usuario switch (key) { case ConsoleKey.A: // mensaje = "Abriendo..."; Console.SetCursorPosition(0, 6); DoEvents(); mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero); mensaje = "Abierto."; break; case ConsoleKey.C: // mensaje = "Cerrando..."; Console.SetCursorPosition(0, 6); DoEvents2(); mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero); mensaje = "Cerrado."; break; } Console.SetCursorPosition(0, 6); Console.Write(" "); Console.SetCursorPosition(0, 6); Console.Write(mensaje); } while (key != ConsoleKey.Escape); } } } Sólo debo modificar o ampliar esa función que falta para dejar el programa más completo.
Saludos.
158
Programación / Scripting / Ejecutar este código de Python en Visual Studio
en: 27 Agosto 2017, 18:49 pm
Buenas:
Tengo un código de Python y quiero ejecutarlo en Visual Studio. Nunca he tratado de hacer ejecutar un código de Python, a ver si sale.
He instalado los componentes necesario.
Código de Python :import os , sys , tkFileDialog, Tkinter
root = Tkinter .Tk ( )
root.withdraw ( )
formats = [ ( 'Roms Super Nintendo SMC' , '.smc' ) , ( 'Roms Super Nintendo SFC' , '.sfc' ) , ( 'Fichier Bin' , '.bin' ) , ( 'Roms Super Nintendo' , '.smc .sfc .bin' ) ]
input = tkFileDialog.askopenfile ( parent= root, mode= 'rb' , filetypes= formats, title= 'Elija el archivo para swapper' )
if not input :
print "¡Imposible de abrir el archivo!"
sys .exit ( )
output = tkFileDialog.asksaveasfile ( parent= root, mode= 'wb' , filetypes= formats, title= 'Elija el archivo de salida' )
if not output:
print "¡No se puede crear el archivo de salida!"
sys .exit ( )
# Lectura del archivo de entrada a un array de bytes
data = bytearray ( input .read ( ) )
# Calculando el tamaño de la habitación en 2 exponentes
expsize = 0
bytesize = len ( data)
while bytesize > 1 :
expsize += 1
bytesize = bytesize // 2
# Unidad de un tamaño adecuado matriz de bytes vacíos
buffer = bytearray ( )
for i in range ( 2 **expsize) : buffer.append ( 0 )
# let's do the swap
count = 0
for i in range ( len ( data) ) :
addr = ( i & 0x7fff ) + ( ( i & 0x008000 ) << ( expsize - 16 ) ) + ( ( i & 0x010000 ) >> 1 ) + ( ( i & 0x020000 ) >> 1 ) + ( ( i & 0x040000 ) >> 1 ) + ( ( i & 0x080000 ) >> 1 ) + ( ( i & 0x100000 ) >> 1 ) + ( ( i & 0x200000 ) >> 1 )
if addr != i: count += 1
buffer[ addr] = data[ i]
print "Swapped %s (%s) addresses" % ( count, hex ( count) )
# Escribir archivo de salida
output.write ( buffer)
# Cerrar carpetas de archivos
input .close ( )
output.close ( )
Creo el proyecto de Python pero no tengo idea donde hay que darle exactamente con todo lo que tiene.
¿Alguna idea?
Saludos.
159
Programación / Java / Pasar código de NetBeans a Eclipse
en: 26 Agosto 2017, 21:51 pm
Hola:
Tengo este código hecho desde NetBeans y quiero adaptarlo a Eclipse. La verdad no sale igual.
NetBeans :
import gnu.io.CommPortIdentifier ;
import gnu.io.SerialPort ;
import gnu.io.SerialPortEvent ;
import gnu.io.SerialPortEventListener ;
import java.io.IOException ;
import java.io.InputStream ;
import java.io.OutputStream ;
import java.util.Enumeration ;
import java.util.TooManyListenersException ;
import java.util.logging.Level ;
import java.util.logging.Logger ;
import javax.swing.JOptionPane ;
/**
*
* @author Ángel Acaymo M. G. (Meta).
*/
//##############################JM################################################
/* La clase debe implementar la interfaz SerialPortEventListener porque esta
misma clase será la encargada de trabajar con el evento escucha cuando reciba
datos el puerto serie. */
public class EP_JAVA_Frame
extends javax.
swing .
JFrame implements SerialPortEventListener
{ //##############################JM################################################
/**
* Creates new form EP_JAVA_Frame
*/
// Variables.
private static final String Led_8_ON
= "Led_8_ON" ; private static final String Led_8_OFF
= "Led_8_OFF" ; private static final String Led_13_ON
= "Led_13_ON" ; private static final String Led_13_OFF
= "Led_13_OFF" ;
// Variables de conexión.
//##############################JM################################################
/* Así como declaraste una variable ouuput para obtener el canal de salida
también creamos una variable para obtener el canal de entrada. */
//##############################JM################################################
SerialPort serialPort;
private final String PUERTO
= "COM4" ; private static final int TIMEOUT = 2000 ; // 2 segundos.
private static final int DATA_RATE = 115200 ; // Baudios.
public EP_JAVA_Frame( ) {
initComponents( ) ;
inicializarConexion( ) ;
}
public void inicializarConexion( ) {
CommPortIdentifier puertoID = null ;
Enumeration puertoEnum
= CommPortIdentifier.
getPortIdentifiers ( ) ;
while ( puertoEnum.hasMoreElements ( ) ) {
CommPortIdentifier actualPuertoID = ( CommPortIdentifier) puertoEnum.nextElement ( ) ;
if ( PUERTO.equals ( actualPuertoID.getName ( ) ) ) {
puertoID = actualPuertoID;
break ;
}
}
if ( puertoID == null ) {
mostrarError( "No se puede conectar al puerto" ) ;
}
try {
serialPort = ( SerialPort) puertoID.open ( this .getClass ( ) .getName ( ) , TIMEOUT) ;
// Parámatros puerto serie.
serialPort.setSerialPortParams ( DATA_RATE, SerialPort.DATABITS_8 , SerialPort.STOPBITS_2 , SerialPort.PARITY_NONE ) ;
output = serialPort.getOutputStream ( ) ;
mostrarError( e.getMessage ( ) ) ;
}
//##############################JM################################################
/* Aquií asignamos el canal de entrada del puerto serie a nuestra variable input,
con sus debido capturador de error. */
try {
input = serialPort.getInputStream ( ) ;
Logger.getLogger ( EP_JAVA_Frame.class .getName ( ) ) .log ( Level.SEVERE , null , ex) ;
}
/* Aquí agregamos el evento de escucha del puerto serial a esta misma clase
(recordamos que nuestra clase implementa SerialPortEventListener), el método que
sobreescibiremos será serialevent. */
try {
serialPort.addEventListener ( this ) ;
serialPort.notifyOnDataAvailable ( true ) ;
Logger.getLogger ( EP_JAVA_Frame.class .getName ( ) ) .log ( Level.SEVERE , null , ex) ;
}
//##############################JM################################################
}
//##############################JM################################################
/* Este evento es el que sobreescribiremos de la interfaz SerialPortEventListener,
este es lanzado cuando se produce un evento en el puerto como por ejemplo
DATA_AVAILABLE (datos recibidos) */
@Override
public void serialEvent( SerialPortEvent spe) {
if ( spe.getEventType ( ) == SerialPortEvent.DATA_AVAILABLE ) {
byte [ ] readBuffer = new byte [ 20 ] ;
try {
int numBytes = 0 ;
while ( input.available ( ) > 0 ) {
numBytes = input.read ( readBuffer) ; //Hacemos uso de la variable input que
//creamos antes, input es nuestro canal de entrada.
}
jTextArea1.
append ( new String ( readBuffer,
0 , numBytes,
"us-ascii" ) ) ; // Convertimos de bytes a String y asignamos al JTEXTAREA.
// Leelos últimos datos.
jTextArea1.setCaretPosition ( jTextArea1.getDocument ( ) .getLength ( ) ) ;
}
}
}
//##############################JM################################################
private void enviarDatos
( String datos
) { try {
output.write ( datos.getBytes ( ) ) ;
mostrarError( "ERROR" ) ;
}
}
public void mostrarError
( String mensaje
) { }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings( "unchecked" )
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents( ) {
jLabel1
= new javax.
swing .
JLabel ( ) ; jLabel2
= new javax.
swing .
JLabel ( ) ; jButton1
= new javax.
swing .
JButton ( ) ; jButton2
= new javax.
swing .
JButton ( ) ; jButton3
= new javax.
swing .
JButton ( ) ; jButton4
= new javax.
swing .
JButton ( ) ; jLabel3
= new javax.
swing .
JLabel ( ) ;
setTitle( "Mini Interfaz Java" ) ;
jLabel1.setText ( "Led 8" ) ;
jLabel2.setText ( "Led 13" ) ;
jButton1.setText ( "ON" ) ;
public void actionPerformed
( java.
awt .
event .
ActionEvent evt
) { jButton1ActionPerformed( evt) ;
}
} ) ;
jButton2.setText ( "OFF" ) ;
public void actionPerformed
( java.
awt .
event .
ActionEvent evt
) { jButton2ActionPerformed( evt) ;
}
} ) ;
jButton3.setText ( "ON" ) ;
public void actionPerformed
( java.
awt .
event .
ActionEvent evt
) { jButton3ActionPerformed( evt) ;
}
} ) ;
jButton4.setText ( "OFF" ) ;
public void actionPerformed
( java.
awt .
event .
ActionEvent evt
) { jButton4ActionPerformed( evt) ;
}
} ) ;
jTextArea1.setColumns ( 20 ) ;
jTextArea1.setRows ( 5 ) ;
jScrollPane1.setViewportView ( jTextArea1) ;
jLabel3.setText ( "Mensajes desde Arduino:" ) ;
javax.swing .GroupLayout layout = new javax.swing .GroupLayout ( getContentPane( ) ) ;
getContentPane( ) .setLayout ( layout) ;
layout.setHorizontalGroup (
layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.addGroup ( layout.createSequentialGroup ( )
.addContainerGap ( )
.addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.
addComponent ( jScrollPane1, javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
217 ,
Short .
MAX_VALUE ) .addGroup ( layout.createSequentialGroup ( )
.addComponent ( jLabel1)
.
addPreferredGap ( javax.
swing .
LayoutStyle .
ComponentPlacement .
RELATED , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) .addComponent ( jLabel2) )
.addGroup ( layout.createSequentialGroup ( )
.addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .TRAILING , false )
.
addComponent ( jButton1, javax.
swing .
GroupLayout .
DEFAULT_SIZE , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) .
addComponent ( jButton2, javax.
swing .
GroupLayout .
DEFAULT_SIZE , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) ) .
addPreferredGap ( javax.
swing .
LayoutStyle .
ComponentPlacement .
RELATED , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) .addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING , false )
.
addComponent ( jButton4, javax.
swing .
GroupLayout .
DEFAULT_SIZE , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) .
addComponent ( jButton3, javax.
swing .
GroupLayout .
DEFAULT_SIZE , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) ) ) .addGroup ( layout.createSequentialGroup ( )
.addComponent ( jLabel3)
.
addGap ( 0 ,
0 ,
Short .
MAX_VALUE ) ) ) .addContainerGap ( ) )
) ;
layout.setVerticalGroup (
layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .LEADING )
.addGroup ( layout.createSequentialGroup ( )
.addContainerGap ( )
.addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .BASELINE )
.addComponent ( jLabel1)
.addComponent ( jLabel2) )
.addPreferredGap ( javax.swing .LayoutStyle .ComponentPlacement .RELATED )
.addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .BASELINE )
.addComponent ( jButton1)
.addComponent ( jButton3) )
.addPreferredGap ( javax.swing .LayoutStyle .ComponentPlacement .RELATED )
.addGroup ( layout.createParallelGroup ( javax.swing .GroupLayout .Alignment .BASELINE )
.addComponent ( jButton2)
.addComponent ( jButton4) )
.addPreferredGap ( javax.swing .LayoutStyle .ComponentPlacement .RELATED )
.addComponent ( jLabel3)
.
addPreferredGap ( javax.
swing .
LayoutStyle .
ComponentPlacement .
RELATED , javax.
swing .
GroupLayout .
DEFAULT_SIZE ,
Short .
MAX_VALUE ) .addComponent ( jScrollPane1, javax.swing .GroupLayout .PREFERRED_SIZE , javax.swing .GroupLayout .DEFAULT_SIZE , javax.swing .GroupLayout .PREFERRED_SIZE )
.addContainerGap ( ) )
) ;
jLabel1.getAccessibleContext ( ) .setAccessibleName ( "jLabel_Led_8" ) ;
jButton1.getAccessibleContext ( ) .setAccessibleName ( "jButton_Led_8_ON" ) ;
jButton2.getAccessibleContext ( ) .setAccessibleName ( "jButton_Led_8_OFF" ) ;
jButton3.getAccessibleContext ( ) .setAccessibleName ( "jButton_Led_13_ON" ) ;
jButton4.getAccessibleContext ( ) .setAccessibleName ( "jButton_Led_13_OFF" ) ;
pack( ) ;
setLocationRelativeTo( null ) ;
} // </editor-fold>
private void jButton1ActionPerformed
( java.
awt .
event .
ActionEvent evt
) { enviarDatos( Led_8_ON) ; // Enciende Led 8.
}
private void jButton2ActionPerformed
( java.
awt .
event .
ActionEvent evt
) { enviarDatos( Led_8_OFF) ; // Apaga Led 8.
}
private void jButton3ActionPerformed
( java.
awt .
event .
ActionEvent evt
) { enviarDatos( Led_13_ON) ; // Enciende Led 13.
}
private void jButton4ActionPerformed
( java.
awt .
event .
ActionEvent evt
) { enviarDatos( Led_13_OFF) ; // Apaga Led 13.
}
/**
* @param args the command line arguments
*/
public static void main
( String args
[ ] ) { /* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
if ( "Nimbus" .equals ( info.getName ( ) ) ) {
javax.
swing .
UIManager .
setLookAndFeel ( info.
getClassName ( ) ) ; break ;
}
}
java.util .logging .Logger .getLogger ( EP_JAVA_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( EP_JAVA_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( EP_JAVA_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
java.util .logging .Logger .getLogger ( EP_JAVA_Frame.class .getName ( ) ) .log ( java.util .logging .Level .SEVERE , null , ex) ;
}
//</editor-fold>
/* Create and display the form */
public void run( ) {
new EP_JAVA_Frame( ) .setVisible ( true ) ;
}
} ) ;
}
// Variables declaration - do not modify
private javax.
swing .
JButton jButton1
; private javax.
swing .
JButton jButton2
; private javax.
swing .
JButton jButton3
; private javax.
swing .
JButton jButton4
; private javax.
swing .
JLabel jLabel1
; private javax.
swing .
JLabel jLabel2
; private javax.
swing .
JLabel jLabel3
; // End of variables declaration
}
Lo he intentado paso por paso, pero no se me da.
Eclipse :
package electronica ;
import gnu.io.CommPortIdentifier ;
import gnu.io.SerialPort ;
import gnu.io.SerialPortEvent ;
import gnu.io.SerialPortEventListener ;
import java.io.IOException ;
import java.io.InputStream ;
import java.io.OutputStream ;
import java.util.Enumeration ;
import java.util.TooManyListenersException ;
import java.util.logging.Level ;
import java.util.logging.Logger ;
import javax.swing.JOptionPane ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import javax.swing.border.EmptyBorder ;
import javax.swing.JButton ;
import javax.swing.JTextArea ;
import java.awt.EventQueue ;
public class EP_Java
extends JFrame {
/**
* Launch the application.
*/
// Variables.
private static final String Led_ON
= "Led_ON" ; private static final String Led_OFF
= "Led_OFF" ;
// Variables de conexión.
SerialPort serialPort;
private final String PUERTO
= "COM4" ; private static final int TIMEOUT = 2000 ; // 2 segundos.
private static final int DATA_RATE = 115200 ; // Baudios.
public static void main
( String [ ] args
) { public void run( ) {
try {
EP_Java frame = new EP_Java( ) ;
frame.setVisible ( true ) ;
e.printStackTrace ( ) ;
}
}
} ) ;
}
public EP_Java( ) {
setTitle( "Encender y apagar un Led - Java y Arduino" ) ;
setDefaultCloseOperation
( JFrame .
EXIT_ON_CLOSE ) ; setBounds( 100 , 100 , 450 , 300 ) ;
setContentPane( contentPane) ;
contentPane.setLayout ( null ) ;
btnOn.setBounds ( 161 , 39 , 89 , 23 ) ;
contentPane.add ( btnOn) ;
btnOff.setBounds ( 161 , 73 , 89 , 23 ) ;
contentPane.add ( btnOff) ;
textArea_Recibir_mensajes.setBounds ( 10 , 103 , 414 , 147 ) ;
contentPane.add ( textArea_Recibir_mensajes) ;
inicializarConexion( ) ;
}
/**
* Create the frame.
*/
public void inicializarConexion( ) {
CommPortIdentifier puertoID = null ;
Enumeration puertoEnum
= CommPortIdentifier.
getPortIdentifiers ( ) ;
while ( puertoEnum.hasMoreElements ( ) ) {
CommPortIdentifier actualPuertoID = ( CommPortIdentifier) puertoEnum.nextElement ( ) ;
if ( PUERTO.equals ( actualPuertoID.getName ( ) ) ) {
puertoID = actualPuertoID;
break ;
}
}
if ( puertoID == null ) {
mostrarError( "No se puede conectar al puerto" ) ;
}
try {
serialPort = ( SerialPort) puertoID.open ( this .getClass ( ) .getName ( ) , TIMEOUT) ;
// Parámatros puerto serie.
serialPort.setSerialPortParams ( DATA_RATE, SerialPort.DATABITS_8 , SerialPort.STOPBITS_2 , SerialPort.PARITY_NONE ) ;
output = serialPort.getOutputStream ( ) ;
mostrarError( e.getMessage ( ) ) ;
}
//##############################JM################################################
/* Aquií asignamos el canal de entrada del puerto serie a nuestra variable input,
con sus debido capturador de error. */
try {
input = serialPort.getInputStream ( ) ;
Logger.getLogger ( EP_Java.class .getName ( ) ) .log ( Level.SEVERE , null , ex) ;
}
/* Aquí agregamos el evento de escucha del puerto serial a esta misma clase
(recordamos que nuestra clase implementa SerialPortEventListener), el método que
sobreescibiremos será serialevent. */
try {
serialPort.addEventListener ( this ) ;
serialPort.notifyOnDataAvailable ( true ) ;
Logger.getLogger ( EP_Java.class .getName ( ) ) .log ( Level.SEVERE , null , ex) ;
}
//##############################JM################################################
}
//##############################JM################################################
/* Este evento es el que sobreescribiremos de la interfaz SerialPortEventListener,
este es lanzado cuando se produce un evento en el puerto como por ejemplo
DATA_AVAILABLE (datos recibidos) */
public void serialEvent( SerialPortEvent spe) {
if ( spe.getEventType ( ) == SerialPortEvent.DATA_AVAILABLE ) {
byte [ ] readBuffer = new byte [ 20 ] ;
try {
int numBytes = 0 ;
while ( input.available ( ) > 0 ) {
numBytes = input.read ( readBuffer) ; //Hacemos uso de la variable input que
//creamos antes, input es nuestro canal de entrada.
}
textArea_Recibir_mensajes.
append ( new String ( readBuffer,
0 , numBytes,
"us-ascii" ) ) ; // Convertimos de bytes a String y asignamos al JTEXTAREA.
// Leelos últimos datos.
textArea_Recibir_mensajes.setCaretPosition ( textArea_Recibir_mensajes.getDocument ( ) .getLength ( ) ) ;
}
}
}
//##############################JM################################################
private void enviarDatos
( String datos
) { try {
output.write ( datos.getBytes ( ) ) ;
mostrarError( "ERROR" ) ;
}
}
public void mostrarError
( String mensaje
) { }
}
¿Alguna idea?
Saludos.
160
Programación / .NET (C#, VB.NET, ASP) / Limpiar textBox en C#
en: 24 Agosto 2017, 22:06 pm
Hola:
En un textbox tengo un contenido, por ejemplo un 0, al hacer clic para escribir, quiero que se borre automáticamente. Nada de seleccoinarlo yo con el ratón y luego borrarlo con Delete. ajjaja.
Lo he intentado de dos maneras y nada.
private void textBox_Tamaño_EEPROM_KeyDown( object sender, KeyEventArgs e)
{
textBox_Tamaño_EEPROM. Clear ( ) ; // Limpiar.
}
Y así:
private void textBox_Tamaño_EEPROM_KeyDown( object sender, KeyEventArgs e)
{
textBox_Tamaño_EEPROM. Text = "" ; // Limpiar.
}
A parte de eso, solo me deja escribir hasta un carácter.