|
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#:using System; using System.Management; // No olvidar y añadir en Dependencias, NuGet. using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace Lector_discos_Net_5_01_cs { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // Variable. public static string datos = ""; [DllImport("winmm.dll")] public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString, int uReturnLength, IntPtr hwndCallback); StringBuilder rt = new StringBuilder (127); private void button_Abrir_Click(object sender, EventArgs e) { label_Mensaje.Text = "Abriendo..."; Application.DoEvents(); discoSiNo(); mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door open", rt, 127, IntPtr.Zero); /* Si quieres por ejemplo elegir la unidad que quieras, en este caso la H, se le asigana !H como indica abajo. En vez de CDAudio, CDAudio!H. mciSendString("set CDAudio!H door open", rt, 127, IntPtr.Zero); */ label_Mensaje.Text = "Abierto."; } private void button_Cerrar_Click(object sender, EventArgs e) { label_Mensaje.Text = "Cerrando..."; Application.DoEvents(); mciSendString("set CDAudio!" + comboBox_Unidad.Text + " door closed", rt, 127, IntPtr.Zero); label_Mensaje.Text = "Cerrado."; label_Mensaje_disco.Text = "Disco en el lector: Leyendo..."; discoSiNo(); } // Lectura de dispositivos. void ConsigueComponentes(string hwclass, string syntax) { ManagementObjectSearcher mos = new ManagementObjectSearcher ("root\\CIMV2", "SELECT * FROM " + hwclass ); foreach (ManagementObject mj in mos.Get()) { if (Convert.ToString(mj[syntax]) != "") { datos = Convert.ToString(mj[syntax]); } } } // Comprobar si hay disco en el lector. void discoSiNo() { // Disco en la unidad del lector. ConsigueComponentes("Win32_CDROMDrive", "MediaLoaded"); // ¿Disco en el lector? if (datos == "True") { label_Mensaje_disco.Text = "Disco en el lector: Sí."; } else { label_Mensaje_disco.Text = "Disco en el lector: No."; } // Limpiar. datos = ""; } private void Form1_Load(object sender, EventArgs e) { discoSiNo(); // Nombre de la unidad. ConsigueComponentes("Win32_CDROMDrive", "Id"); comboBox_Unidad.Items.Add(datos); comboBox_Unidad.Text = datos.ToString(); } } }
Código WindowsForm .Net 5.0:namespace Lector_discos_Net_5_01_cs { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button_Abrir = new System.Windows.Forms.Button(); this.button_Cerrar = new System.Windows.Forms.Button(); this.groupBox_Bandeja = new System.Windows.Forms.GroupBox(); this.label_Mensaje = new System.Windows.Forms.Label(); this.comboBox_Unidad = new System.Windows.Forms.ComboBox(); this.label_Unidad = new System.Windows.Forms.Label(); this.label_Mensaje_disco = new System.Windows.Forms.Label(); this.groupBox_Bandeja.SuspendLayout(); this.SuspendLayout(); // // button_Abrir // this.button_Abrir.Location = new System.Drawing.Point(32, 146); this.button_Abrir.Name = "button_Abrir"; this.button_Abrir.Size = new System.Drawing.Size(92, 47); this.button_Abrir.TabIndex = 0; this.button_Abrir.Text = "&Abrir"; this.button_Abrir.UseVisualStyleBackColor = true; this.button_Abrir.Click += new System.EventHandler(this.button_Abrir_Click); // // button_Cerrar // this.button_Cerrar.Location = new System.Drawing.Point(155, 146); this.button_Cerrar.Name = "button_Cerrar"; this.button_Cerrar.Size = new System.Drawing.Size(92, 47); this.button_Cerrar.TabIndex = 1; this.button_Cerrar.Text = "&Cerrar"; this.button_Cerrar.UseVisualStyleBackColor = true; this.button_Cerrar.Click += new System.EventHandler(this.button_Cerrar_Click); // // groupBox_Bandeja // this.groupBox_Bandeja.Controls.Add(this.label_Mensaje); this.groupBox_Bandeja.Location = new System.Drawing.Point(12, 12); this.groupBox_Bandeja.Name = "groupBox_Bandeja"; this.groupBox_Bandeja.Size = new System.Drawing.Size(249, 117); this.groupBox_Bandeja.TabIndex = 2; this.groupBox_Bandeja.TabStop = false; this.groupBox_Bandeja.Text = "Bandeja:"; // // label_Mensaje // this.label_Mensaje.AutoSize = true; this.label_Mensaje.Font = new System.Drawing.Font("Segoe UI", 27 .75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.label_Mensaje.Location = new System.Drawing.Point(20, 40); this.label_Mensaje.Name = "label_Mensaje"; this.label_Mensaje.Size = new System.Drawing.Size(54, 50); this.label_Mensaje.TabIndex = 0; this.label_Mensaje.Text = "¿?"; // // comboBox_Unidad // this.comboBox_Unidad.FormattingEnabled = true; this.comboBox_Unidad.Location = new System.Drawing.Point(310, 159); this.comboBox_Unidad.Name = "comboBox_Unidad"; this.comboBox_Unidad.Size = new System.Drawing.Size(121, 23); this.comboBox_Unidad.TabIndex = 3; // // label_Unidad // this.label_Unidad.AutoSize = true; this.label_Unidad.Location = new System.Drawing.Point(310, 132); this.label_Unidad.Name = "label_Unidad"; this.label_Unidad.Size = new System.Drawing.Size(48, 15); this.label_Unidad.TabIndex = 4; this.label_Unidad.Text = "Unidad:"; // // label_Mensaje_disco // this.label_Mensaje_disco.AutoSize = true; this.label_Mensaje_disco.Font = new System.Drawing.Font("Segoe UI", 21 .75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); this.label_Mensaje_disco.Location = new System.Drawing.Point(12, 198); this.label_Mensaje_disco.Name = "label_Mensaje_disco"; this.label_Mensaje_disco.Size = new System.Drawing.Size(269, 40); this.label_Mensaje_disco.TabIndex = 5; this.label_Mensaje_disco.Text = "Disco en el lector: "; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(463, 247); this.Controls.Add(this.label_Mensaje_disco); this.Controls.Add(this.label_Unidad); this.Controls.Add(this.comboBox_Unidad); this.Controls.Add(this.button_Abrir); this.Controls.Add(this.groupBox_Bandeja); this.Controls.Add(this.button_Cerrar); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Lector disco C# 2019 - .Net 5.0"; this.Load += new System.EventHandler(this.Form1_Load); this.groupBox_Bandeja.ResumeLayout(false); this.groupBox_Bandeja.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button_Abrir; private System.Windows.Forms.Button button_Cerrar; private System.Windows.Forms.GroupBox groupBox_Bandeja; private System.Windows.Forms.Label label_Mensaje; private System.Windows.Forms.ComboBox comboBox_Unidad; private System.Windows.Forms.Label label_Unidad; private System.Windows.Forms.Label label_Mensaje_disco; } }
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.
|
|
|
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. title Arduino CMD y puerto serie MODE.com COM4 BAUD=115200 PARITY=n DATA=8 STOP=1 :Menu CLS CHOICE.exe /C "123" /M " Escoge una opción " ) )
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: 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. using System; using System.IO; namespace Informacion_lector_Consola_01 { class Program { static void Main(string[] args) { #region Configuración ventana. // Título de la ventana. Console.Title = "Información lector."; // Tamaño de la ventana, x, y. Console.SetWindowSize(80, 35); // Color de fondo. Console.BackgroundColor = ConsoleColor.White; // Color de las letras. Console.ForegroundColor = ConsoleColor.Black; // Limpiar pantalla y dejarlo todo en color de fondo. Console.Clear(); // Visible el cursor. Console.CursorVisible = true; #endregion DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Unidad {0}", d.Name); Console.WriteLine(" Tipo de unidad: {0}", d.DriveType); if (d.IsReady == true) { Console.WriteLine(" Etiqueta de volumen : {0}", d.VolumeLabel); Console.WriteLine(" Sistema de archivo: {0}", d.DriveFormat); Console.WriteLine( " Espacio disponible para el usuario actual:{0, 15} bytes", d.AvailableFreeSpace); Console.WriteLine( " Espacio total disponible: {0, 15} bytes", d.TotalFreeSpace); Console.WriteLine( " Tamaño total de la unidad: {0, 15} bytes ", d.TotalSize); } } // Pulse cualquier tecla para continuar. Console.ReadKey(); } } }
¿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.
|
|
|
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. # 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-cdromdriveQuiero que me detecte las unidades y lo muestre en un comboBox. Creo una función. private static void GetMyCPUInfo(string hwclass, string syntax) { ManagementObjectSearcher mos = new ManagementObjectSearcher ("root\\CIMV2", "SELECT * FROM " + hwclass ); foreach (ManagementObject mj in mos.Get()) { Console.WriteLine(Convert.ToString(mj[syntax])); } }
Con esto llamo una unidad. GetMyCPUInfo("Win32_CDROMDrive", "Id");
Añado los datos en el comboBox así. comboBox_Unidad.Items.Add(datos);
Pues no me sale. ¿Alguna idea? Saludos.
|
|
|
|
|
|
|