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


Tema destacado: Como proteger una cartera - billetera de Bitcoin


  Mostrar Mensajes
Páginas: 1 ... 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 [27] 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 ... 261
261  Programación / .NET (C#, VB.NET, ASP) / Re: Añadir elementos al comboBox en: 29 Marzo 2021, 21:25 pm
Buenas:

Lo he intentado hacerlo en Windows Form con.Net 5.0.




Código fuente C#
:

Código
  1. using System;
  2. using System.Management; // No olvidar y añadir en Dependencias, NuGet.
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. using System.Windows.Forms;
  6.  
  7. namespace Lector_discos_Net_5_01_cs
  8. {
  9.    public partial class Form1 : Form
  10.    {
  11.        public Form1()
  12.        {
  13.            InitializeComponent();
  14.        }
  15.  
  16.        // Variable.
  17.        public static string datos = "";
  18.  
  19.        [DllImport("winmm.dll")]
  20.        public static extern Int32 mciSendString(string lpstrCommand,
  21.            StringBuilder lpstrReturnString,
  22.            int uReturnLength,
  23.            IntPtr hwndCallback);
  24.  
  25.        StringBuilder rt = new StringBuilder(127);
  26.  
  27.        private void button_Abrir_Click(object sender, EventArgs e)
  28.        {
  29.            label_Mensaje.Text = "Abriendo...";
  30.            Application.DoEvents();
  31.            discoSiNo();
  32.            mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door open", rt, 127, IntPtr.Zero);
  33.  
  34.            /*
  35.                Si quieres por ejemplo elegir la unidad que quieras, en este caso la H, se le asigana !H
  36.                como indica abajo. En vez de CDAudio, CDAudio!H.
  37.                mciSendString("set CDAudio!H door open", rt, 127, IntPtr.Zero);
  38.             */
  39.  
  40.            label_Mensaje.Text = "Abierto.";
  41.  
  42.        }
  43.  
  44.        private void button_Cerrar_Click(object sender, EventArgs e)
  45.        {
  46.            label_Mensaje.Text = "Cerrando...";
  47.            Application.DoEvents();
  48.            mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door closed", rt, 127, IntPtr.Zero);
  49.            label_Mensaje.Text = "Cerrado.";
  50.            label_Mensaje_disco.Text = "Disco en el lector: Leyendo...";
  51.            discoSiNo();
  52.        }
  53.  
  54.        // Lectura de dispositivos.
  55.        void ConsigueComponentes(string hwclass, string syntax)
  56.        {
  57.            ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
  58.            foreach (ManagementObject mj in mos.Get())
  59.            {
  60.                if (Convert.ToString(mj[syntax]) != "")
  61.                {
  62.                    datos = Convert.ToString(mj[syntax]);
  63.                }
  64.            }
  65.        }
  66.  
  67.        // Comprobar si hay disco en el lector.
  68.        void discoSiNo()
  69.        {
  70.            // Disco en la unidad del lector.
  71.            ConsigueComponentes("Win32_CDROMDrive", "MediaLoaded");
  72.  
  73.            // ¿Disco en el lector?
  74.            if (datos == "True")
  75.            {
  76.                label_Mensaje_disco.Text = "Disco en el lector: Sí.";
  77.            }
  78.  
  79.            else
  80.            {
  81.                label_Mensaje_disco.Text = "Disco en el lector: No.";
  82.            }
  83.  
  84.            // Limpiar.
  85.            datos = "";
  86.  
  87.        }
  88.  
  89.        private void Form1_Load(object sender, EventArgs e)
  90.        {
  91.            discoSiNo();
  92.  
  93.            // Nombre de la unidad.
  94.            ConsigueComponentes("Win32_CDROMDrive", "Id");
  95.  
  96.            comboBox_Unidad.Items.Add(datos);
  97.            comboBox_Unidad.Text = datos.ToString();
  98.        }
  99.    }
  100. }


Código WindowsForm .Net 5.0
:

Código
  1. namespace Lector_discos_Net_5_01_cs
  2. {
  3.    partial class Form1
  4.    {
  5.        /// <summary>
  6.        ///  Required designer variable.
  7.        /// </summary>
  8.        private System.ComponentModel.IContainer components = null;
  9.  
  10.        /// <summary>
  11.        ///  Clean up any resources being used.
  12.        /// </summary>
  13.        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  14.        protected override void Dispose(bool disposing)
  15.        {
  16.            if (disposing && (components != null))
  17.            {
  18.                components.Dispose();
  19.            }
  20.            base.Dispose(disposing);
  21.        }
  22.  
  23.        #region Windows Form Designer generated code
  24.  
  25.        /// <summary>
  26.        ///  Required method for Designer support - do not modify
  27.        ///  the contents of this method with the code editor.
  28.        /// </summary>
  29.        private void InitializeComponent()
  30.        {
  31.            this.button_Abrir = new System.Windows.Forms.Button();
  32.            this.button_Cerrar = new System.Windows.Forms.Button();
  33.            this.groupBox_Bandeja = new System.Windows.Forms.GroupBox();
  34.            this.label_Mensaje = new System.Windows.Forms.Label();
  35.            this.comboBox_Unidad = new System.Windows.Forms.ComboBox();
  36.            this.label_Unidad = new System.Windows.Forms.Label();
  37.            this.label_Mensaje_disco = new System.Windows.Forms.Label();
  38.            this.groupBox_Bandeja.SuspendLayout();
  39.            this.SuspendLayout();
  40.            //
  41.            // button_Abrir
  42.            //
  43.            this.button_Abrir.Location = new System.Drawing.Point(32, 146);
  44.            this.button_Abrir.Name = "button_Abrir";
  45.            this.button_Abrir.Size = new System.Drawing.Size(92, 47);
  46.            this.button_Abrir.TabIndex = 0;
  47.            this.button_Abrir.Text = "&Abrir";
  48.            this.button_Abrir.UseVisualStyleBackColor = true;
  49.            this.button_Abrir.Click += new System.EventHandler(this.button_Abrir_Click);
  50.            //
  51.            // button_Cerrar
  52.            //
  53.            this.button_Cerrar.Location = new System.Drawing.Point(155, 146);
  54.            this.button_Cerrar.Name = "button_Cerrar";
  55.            this.button_Cerrar.Size = new System.Drawing.Size(92, 47);
  56.            this.button_Cerrar.TabIndex = 1;
  57.            this.button_Cerrar.Text = "&Cerrar";
  58.            this.button_Cerrar.UseVisualStyleBackColor = true;
  59.            this.button_Cerrar.Click += new System.EventHandler(this.button_Cerrar_Click);
  60.            //
  61.            // groupBox_Bandeja
  62.            //
  63.            this.groupBox_Bandeja.Controls.Add(this.label_Mensaje);
  64.            this.groupBox_Bandeja.Location = new System.Drawing.Point(12, 12);
  65.            this.groupBox_Bandeja.Name = "groupBox_Bandeja";
  66.            this.groupBox_Bandeja.Size = new System.Drawing.Size(249, 117);
  67.            this.groupBox_Bandeja.TabIndex = 2;
  68.            this.groupBox_Bandeja.TabStop = false;
  69.            this.groupBox_Bandeja.Text = "Bandeja:";
  70.            //
  71.            // label_Mensaje
  72.            //
  73.            this.label_Mensaje.AutoSize = true;
  74.            this.label_Mensaje.Font = new System.Drawing.Font("Segoe UI", 27.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
  75.            this.label_Mensaje.Location = new System.Drawing.Point(20, 40);
  76.            this.label_Mensaje.Name = "label_Mensaje";
  77.            this.label_Mensaje.Size = new System.Drawing.Size(54, 50);
  78.            this.label_Mensaje.TabIndex = 0;
  79.            this.label_Mensaje.Text = "¿?";
  80.            //
  81.            // comboBox_Unidad
  82.            //
  83.            this.comboBox_Unidad.FormattingEnabled = true;
  84.            this.comboBox_Unidad.Location = new System.Drawing.Point(310, 159);
  85.            this.comboBox_Unidad.Name = "comboBox_Unidad";
  86.            this.comboBox_Unidad.Size = new System.Drawing.Size(121, 23);
  87.            this.comboBox_Unidad.TabIndex = 3;
  88.            //
  89.            // label_Unidad
  90.            //
  91.            this.label_Unidad.AutoSize = true;
  92.            this.label_Unidad.Location = new System.Drawing.Point(310, 132);
  93.            this.label_Unidad.Name = "label_Unidad";
  94.            this.label_Unidad.Size = new System.Drawing.Size(48, 15);
  95.            this.label_Unidad.TabIndex = 4;
  96.            this.label_Unidad.Text = "Unidad:";
  97.            //
  98.            // label_Mensaje_disco
  99.            //
  100.            this.label_Mensaje_disco.AutoSize = true;
  101.            this.label_Mensaje_disco.Font = new System.Drawing.Font("Segoe UI", 21.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
  102.            this.label_Mensaje_disco.Location = new System.Drawing.Point(12, 198);
  103.            this.label_Mensaje_disco.Name = "label_Mensaje_disco";
  104.            this.label_Mensaje_disco.Size = new System.Drawing.Size(269, 40);
  105.            this.label_Mensaje_disco.TabIndex = 5;
  106.            this.label_Mensaje_disco.Text = "Disco en el lector: ";
  107.            //
  108.            // Form1
  109.            //
  110.            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
  111.            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  112.            this.ClientSize = new System.Drawing.Size(463, 247);
  113.            this.Controls.Add(this.label_Mensaje_disco);
  114.            this.Controls.Add(this.label_Unidad);
  115.            this.Controls.Add(this.comboBox_Unidad);
  116.            this.Controls.Add(this.button_Abrir);
  117.            this.Controls.Add(this.groupBox_Bandeja);
  118.            this.Controls.Add(this.button_Cerrar);
  119.            this.Name = "Form1";
  120.            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
  121.            this.Text = "Lector disco C# 2019 - .Net 5.0";
  122.            this.Load += new System.EventHandler(this.Form1_Load);
  123.            this.groupBox_Bandeja.ResumeLayout(false);
  124.            this.groupBox_Bandeja.PerformLayout();
  125.            this.ResumeLayout(false);
  126.            this.PerformLayout();
  127.  
  128.        }
  129.  
  130.        #endregion
  131.  
  132.        private System.Windows.Forms.Button button_Abrir;
  133.        private System.Windows.Forms.Button button_Cerrar;
  134.        private System.Windows.Forms.GroupBox groupBox_Bandeja;
  135.        private System.Windows.Forms.Label label_Mensaje;
  136.        private System.Windows.Forms.ComboBox comboBox_Unidad;
  137.        private System.Windows.Forms.Label label_Unidad;
  138.        private System.Windows.Forms.Label label_Mensaje_disco;
  139.    }
  140. }

Aquí se trata que no me sale. Es que tengo dos unidades de disco CD-ROM / DVD-ROM.
Se me agrega solo la F:, Falta la G:, pero siempre que sea sea unidad de disco.

Saludos.
262  Programación / .NET (C#, VB.NET, ASP) / Re: ¿Cómo listar solo unidades DVD y ver su información? en: 29 Marzo 2021, 21:07 pm
Muchísimas gracias. Voy a experimentar.

  ;-) ;-) ;-)
263  Programación / Scripting / Recibir mensajes en: 28 Marzo 2021, 14:39 pm
Quiero recibir mensajes desde el puerto serie usando CMD de Windwos.

Creo un Script gracias a los compañeros de este foro en su día.
Código
  1.    @Echo OFF
  2.    title Arduino CMD y puerto serie
  3.  
  4.    CHCP 1252 >Nul
  5.    MODE.com COM4 BAUD=115200 PARITY=n DATA=8 STOP=1
  6.    :Menu
  7.        CLS
  8.        echo.
  9.        echo.
  10.        echo.                   1.- Luz  ON
  11.        echo.
  12.        echo.                   2.- Luz  OFF
  13.        echo.
  14.        echo.                   3.- Salir
  15.        echo.
  16.        echo.
  17.        echo.
  18.  
  19.        CHOICE.exe /C "123" /M "                   Escoge una opción "
  20.        echo.
  21.        echo.
  22.        echo.
  23.  
  24.        If %ErrorLevel% EQU 1 (
  25.            copy puerto_Luz_ON.txt  COM1:
  26.            echo Puerto COM1: B
  27.            timeout 5 >nul
  28.            goto Menu
  29.        )
  30.  
  31.        If %ErrorLevel% EQU 2 (
  32.            copy puerto_Luz_OFF.txt COM1:
  33.            echo Puerto COM1: X72
  34.            timeout 5 >nul
  35.            goto Menu
  36.        )
  37.  
  38.        Pause
  39.  
  40.        Exit /B

La cuestión es.

¿Cómo se recibe un mensaje desde el otro lado del puerto serie?

Saludos.
264  Programación / .NET (C#, VB.NET, ASP) / ¿Cómo listar solo unidades DVD y ver su información? en: 28 Marzo 2021, 12:12 pm
Quiero hacer un programa en consola C#, en el cual me muestre cuantas hay y su información. Solo quiero que me muestre unidades de discos DVD, aunque sean SATA, IDE o por USB.

Por ejemplo:
Citar
Unidad F:
     Etiqueta de volumen : 58 Fotos 2020 Tamaño total de la unidad: 4,26 GB.

Unidad G:
     Etiqueta de volumen : Visual Tamaño total de la unidad: 3,09 GB.

Quiero hacerlo así y ya está. El ejemplo que he visto te cuenta todas las unidades como indica abajo y no me interesa.
Código
  1. using System;
  2. using System.IO;
  3.  
  4. namespace Informacion_lector_Consola_01
  5. {
  6.    class Program
  7.    {
  8.        static void Main(string[] args)
  9.        {
  10.            #region Configuración ventana.
  11.            // Título de la ventana.
  12.            Console.Title = "Información lector.";
  13.  
  14.            // Tamaño de la ventana, x, y.
  15.            Console.SetWindowSize(80, 35);
  16.  
  17.            // Color de fondo.
  18.            Console.BackgroundColor = ConsoleColor.White;
  19.  
  20.            // Color de las letras.
  21.            Console.ForegroundColor = ConsoleColor.Black;
  22.  
  23.            // Limpiar pantalla y dejarlo todo en color de fondo.
  24.            Console.Clear();
  25.  
  26.            // Visible el cursor.
  27.            Console.CursorVisible = true;
  28.            #endregion
  29.  
  30.            DriveInfo[] allDrives = DriveInfo.GetDrives();
  31.  
  32.            foreach (DriveInfo d in allDrives)
  33.            {
  34.                Console.WriteLine("Unidad {0}", d.Name);
  35.                Console.WriteLine("  Tipo de unidad:                 {0}", d.DriveType);
  36.                if (d.IsReady == true)
  37.                {
  38.                    Console.WriteLine("  Etiqueta de volumen :       {0}", d.VolumeLabel);
  39.                    Console.WriteLine("  Sistema de archivo:         {0}", d.DriveFormat);
  40.                    Console.WriteLine(
  41.                        "  Espacio disponible para el usuario actual:{0, 15} bytes",
  42.                        d.AvailableFreeSpace);
  43.  
  44.                    Console.WriteLine(
  45.                        "  Espacio total disponible:                 {0, 15} bytes",
  46.                        d.TotalFreeSpace);
  47.  
  48.                    Console.WriteLine(
  49.                        "  Tamaño total de la unidad:                {0, 15} bytes ",
  50.                        d.TotalSize);
  51.                }
  52.            }
  53.  
  54.            // Pulse cualquier tecla para continuar.
  55.            Console.ReadKey();
  56.        }
  57.    }
  58. }

¿Alguna idea?

Saludos.
265  Informática / Hardware / Controlar DVD en: 28 Marzo 2021, 01:02 am
Buenas:

1) ¿Es posible controlar el encendido y apagado del Led que viene en el lector de un DVD como este de abajo?



2) Windows sabe cuando hay un disco en la lectora o no. ¿Windows sabe cuando el lector está abierto o cerrado?

Saludos.
266  Informática / Hardware / Re: PC no enciende mediante botón ni puente en: 28 Marzo 2021, 00:25 am
267  Programación / Scripting / No me deja enviar mensaje en: 26 Marzo 2021, 22:21 pm
Hola:

Este Script se trata de que quiero enviar por ejemplo la letra B, o esto otro como X72. Si envío un comando o mensaje llamado B. Me tiene que llegar una respuesta. No hace nada.

Los datos son enviados al puerto serie.

Este es el código.
Código:
# Para comprobar los puertos series disponibles en el sistema:
[System.IO.Ports.SerialPort]::getportnames()
 
# O bien de una manera más exhaustiva:
Get-WMIObject Win32_SerialPort
 
# Establecer los parámetros básicos de conexión. Una tipica conexión 9600 bps, 8N1 sin control de flujo sería la siguiente:
$puertoCOM = "COM1"  # El puerto serie que se quiere emplear
$bps = 2400 # La tasa de baudios por segundo del puerto. Típicos valores entre 1200 (o incluso menos) y 115200 (o incluso más)
$paridad = [System.IO.Ports.Parity]::None # Paridad de datos. Puede ser Even (par), Odd (impar) o None (sin paridad) 
$dataBits = 8 # Bits de datos. Puede ser 7 u 8
$stopBits = [System.IO.Ports.StopBits]::one # Bits de parada. Puede ser one (1), onepointfive (1.5) o two (dos)
$puerto = New-Object System.IO.Ports.SerialPort $puertoCOM,$bps,$paridad,$dataBits,$stopBits   # Crea la nueva instancia
 
# Se pueden establecer otros parámetros, como la activación del control del flujo por RTS/CTS , DTR/DSR, Handshake, fijar el tamaño de los buffers de lectura y escritura o establecer los timeouts de lectura. Todos estos parámetros, así como el estado general del resto, se pueden consultar llamando al objeto:
$puerto
$puerto.ReadTimeout = 500   # Establece un timeout de lectura de 500 mseg
$puerto.WriteTimeout = 500 # Establece un timeout de escritura de 250 mseg
 
# Abre el puerto
$puerto.Open()
 
# Lectura del puerto
$mensaje=$puerto.ReadLine()
 
# Escritura del puerto
$mensaje="B"
$puerto.WriteLine($mensaje)
 
# Cierra el puerto
$puerto.Close()

Quiero saber que es lo que ocurre.

Gracias.
268  Programación / .NET (C#, VB.NET, ASP) / Añadir elementos al comboBox en: 25 Marzo 2021, 22:05 pm
Buenas:

Estoy todo el rato intentando que me lea todos los lectores que tenga en un Pc o ordenador sea IDE, SATA o un lector externo por USB de discos, DVD en este caso.

Mirando aquí he encontrado esto.
https://docs.microsoft.com/es-es/windows/win32/cimwin32prov/win32-cdromdrive

Quiero que me detecte las unidades y lo muestre en un comboBox.

Creo una función.
Código
  1.        private static void GetMyCPUInfo(string hwclass, string syntax)
  2.        {
  3.            ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
  4.            foreach (ManagementObject mj in mos.Get())
  5.            {
  6.                Console.WriteLine(Convert.ToString(mj[syntax]));
  7.            }
  8.        }

Con esto llamo una unidad.
Código
  1. GetMyCPUInfo("Win32_CDROMDrive", "Id");

Añado los datos en el comboBox así.
Código
  1. comboBox_Unidad.Items.Add(datos);

Pues no me sale.

¿Alguna idea?

Saludos.
269  Programación / .NET (C#, VB.NET, ASP) / Re: Usar un buen delimitador en: 25 Marzo 2021, 20:44 pm
Entendido.

Muchísimas gracias.

 ;-) ;-) ;-) ;-)
270  Programación / .NET (C#, VB.NET, ASP) / Re: Usar un buen delimitador en: 25 Marzo 2021, 17:40 pm
Muchas gracias.

El primero funciona de maravilla, exceptuando qu een medio se ponen 0 y no se el motivo. ;)
Páginas: 1 ... 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 [27] 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 ... 261
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines