171
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.
172
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.
173
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.
174
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.
175
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.
176
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.
177
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.
178
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.
179
Programación / .NET (C#, VB.NET, ASP) / Calcular porcentaje
en: 21 Agosto 2017, 12:50 pm
Hola:
Hice esta aplicación para enviar datos a EEPROM tipo 24LCxx por I2C con Arduino. Tabajando con C#, ya puedo enviar los datos al puerto serie. Puede contar los bytes enviados. El problema, que estoy machacando la cabeza que no hay manera de hacer fucnionar en la barra del progreso que me cuenta el "label_Por_ciento" del 0 % al 100 %.
Ya puedeo envair datos y cancelarlo.
private void TestDoEvents( )
{
byte [ ] archivo = File. ReadAllBytes ( textBox_ubicacion_archivo. Text ) ; // Carga el archivo en el array.
progressBar_barrra_progreso. Maximum = archivo. Length ; // Hasta donde llegue el tamaño del archivo.
for ( int i = 0 ; i <= archivo. GetUpperBound ( 0 ) ; i++ )
{
serialPort1. Write ( archivo, i, 1 ) ;
progressBar_barrra_progreso. Value = i;
label_Bytes_transmitidos. Text = i. ToString ( ) + " Bytes." ;
Application. DoEvents ( ) ;
if ( alto == true )
{
alto = false ;
break ; // TODO: might not be correct. Was : Exit For
}
}
button_Cancelar. Text = "Arranque" ;
}
Botón.
private void button_Cancelar_Click( object sender, EventArgs e)
{
if ( button_Cancelar. Text == "Arranque" )
{
button_Cancelar. Text = "Cancelar" ;
TestDoEvents( ) ;
progressBar_barrra_progreso. Value = 0 ; // Resetear progressBar a 0.
label_Bytes_transmitidos. Text = "0" ;
}
else
{
if ( alto == true )
{
alto = false ;
}
else
{
alto = true ;
button_Cancelar. Text = "Arranque" ;
}
}
}
¿Alguna idea?
Saludos.
180
Programación / Java / Encontrar error en el código
en: 18 Agosto 2017, 01:48 am
Hola:
Uso Eclipse oxigeny. En el JFrame puse en el formulario un JButton y un JTextArea. Mi idea es que si pulsas el botón "Mostrar", siga en el JTextArea el mensaje: Hola mundo.
Pulso dos veces el botón Mostrar y me lleva alcódigo.
// Variable tipo String. String variable = "Hola mundo."; // Mostramos el contenido de la variable en el JTextArea. textArea.append(variable); La palabra textArea que es el nombre del JTextArea marca error. No lo detecta. El error indicado es este:
Description Resource Path Location Type textArea cannot be resolved Prueba01.java /Proyectazo/src/ejercicios line 53 Java Problem Código completo:
package ejercicios; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import javax.swing.JTextArea; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Prueba01 extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Prueba01 frame = new Prueba01(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Prueba01() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton btnMostrar = new JButton("Mostrar"); btnMostrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Variable tipo String. String variable = "Hola mundo."; // Mostramos el contenido de la variable en el JTextArea. textArea.append(variable); } }); btnMostrar.setBounds(165, 11, 89, 23); contentPane.add(btnMostrar); JTextArea textArea = new JTextArea(); textArea.setBounds(10, 55, 414, 195); contentPane.add(textArea); } } ¿Alguna idea?
Saludos.