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

 

 


Tema destacado: Introducción a Git (Primera Parte)


  Mostrar Mensajes
Páginas: 1 ... 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 [45] 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 ... 255
441  Programación / .NET (C#, VB.NET, ASP) / Re: Imprimir una hoja con C# en: 29 Marzo 2018, 08:00 am
Buenas:

Pedazo de cocumento, has hecho un buen trabajo. ;)

Me ha ayudado tener ideas, ya puedo imprimir un folio, eso si, me sale una ventana con un botón cancelar y la palabra diciendo "Imprimiendo..." que no debería, pero al menos ya funciona. Dejo el código por si alguien lo necesita o coja ideas.

Código C#:
Código
  1. using System;
  2. using System.Drawing; // No olvidar y añadir referencia.
  3. using System.Drawing.Printing;
  4.  
  5. namespace Impresora_Consola_01
  6. {
  7.    class Program
  8.    {
  9.        static void Main(string[] args)
  10.        {
  11.            string s = @"Hola amigo.
  12.  
  13. Solo te he gastado un folio.";
  14.  
  15.            PrintDocument p = new PrintDocument();
  16.            p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
  17.            {
  18.                e1.Graphics.DrawString(s, new Font("Times New Roman", 12),
  19.                    new SolidBrush(Color.Black), new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width,
  20.                    p.DefaultPageSettings.PrintableArea.Height));
  21.            };
  22.  
  23.            try
  24.            {
  25.                p.Print();
  26.            }
  27.            catch (Exception ex)
  28.            {
  29.                // throw new Exception("Exception Occured While Printing", ex);
  30.            }
  31.        }
  32.    }
  33. }

Gracias por tu tiempo.
442  Programación / .NET (C#, VB.NET, ASP) / Imprimir una hoja con C# en: 27 Marzo 2018, 21:46 pm
Buenas:

Quiero imprimir un folio, una hoja con la consola en C#, no con Windows Form.
Aquí hay un ejemplo pero es con Windows Form en el cual no me interesa.
https://msdn.microsoft.com/es-es/library/system.drawing.printing.printersettings%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp&f=255&MSPPError=-2147217396#code-snippet-2

He modificado el código así un poco.
Código
  1. using System;
  2. using System.IO;
  3.  
  4.  
  5. namespace Impresora_Consola_01
  6. {
  7.    class Program
  8.    {
  9.        static void Main(string[] args)
  10.        {
  11.            void Printing(string printer)
  12.            {
  13.                try
  14.                {
  15.                    streamToPrint = new StreamReader(@"Hola amigo.");
  16.                    try
  17.                    {
  18.                        printFont = new Font("Arial", 10);
  19.                        PrintDocument pd = new PrintDocument();
  20.                        pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
  21.                        // Specify the printer to use.
  22.                        pd.PrinterSettings.PrinterName = printer;
  23.  
  24.                        if (pd.PrinterSettings.IsValid)
  25.                        {
  26.                            pd.Print();
  27.                        }
  28.                        else
  29.                        {
  30.                            Console.WriteLine("Printer is invalid.");
  31.                        }
  32.                    }
  33.                    finally
  34.                    {
  35.                        streamToPrint.Close();
  36.                    }
  37.                }
  38.                catch (Exception ex)
  39.                {
  40.                    Console.WriteLine(ex.Message);
  41.                }
  42.            }
  43.        }
  44.    }
  45. }
  46.  

Cuando ejecutes el ejecutable, lo que tiene que hacer, buscar una impresora que tenga dispuesta, y imprima solo un folio. El mensaje que imprime una hoja es este:

Citar
Hola amigo.

Solo te he gastado un folio.

¿Es posible hacer en modo consola o tiene que ser si o si con Windows Form?

Saludos.
443  Programación / .NET (C#, VB.NET, ASP) / Re: Programas de broma en: 23 Marzo 2018, 21:54 pm
Siguiendo los consejos que dieron arriba sobre regedit, lo hice así y funciona.

Código
  1. using Microsoft.Win32;
  2. using System;
  3. using System.IO;
  4.  
  5. namespace Broma_Consola_03
  6. {
  7.    class Program
  8.    {
  9.        static void Main(string[] args)
  10.        {
  11.            // Root.
  12.            const string userRoot = "HKEY_CURRENT_USER";
  13.            // Clave.
  14.            const string subkey = "Metaconta";
  15.            // FullName.
  16.            const string keyName = userRoot + "\\" + subkey;
  17.            // ValueName.
  18.            const string valueName = "Contador";
  19.  
  20.            // Variables txt.
  21.            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  22.  
  23.            // Si no existe la Key, dará -1.
  24.            int contador = Convert.ToInt32(Registry.GetValue(keyName, valueName, -1) ?? -1);
  25.  
  26.            // Comprueba si la key, al ser -1 si la key no existe.
  27.            if (contador >= 0)
  28.            {
  29.                // Si el contador es mayor que 0.
  30.                if (contador > 0)
  31.                {
  32.                    // Sobre escribe la key con -1 su valor.
  33.                    Registry.SetValue(keyName, valueName, contador -= 1);
  34.                }
  35.  
  36.                // Si el contador es igual a 0.
  37.                if (contador == 0)
  38.                {
  39.                    // Escribe un nuevo arhivo de texto con su contenido correspondiente.
  40.                    File.WriteAllText(Path.Combine(path, "Hola.txt"), "Hola amigo.");
  41.                }
  42.  
  43.            }
  44.            // Entonces.
  45.            else
  46.            {
  47.                // Escribe en el registro el valor.
  48.                Registry.SetValue(keyName, valueName, 3);
  49.            }
  50.        }
  51.    }
  52. }

Saludos.
444  Programación / .NET (C#, VB.NET, ASP) / Re: Programas de broma en: 22 Marzo 2018, 22:17 pm
Buenas compeñar@s:

Muy buen aporte. No había caído la parte esta del inicio.
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

Si no está en modo administrador, nose si tendrás permiso o Windows 10 se queja. Tengo que hacer pruebas.

Buen tutorial.

Gracias a todos por aportar, modificaré con vuestros aportes usando el regedit.

Saludos..
445  Programación / .NET (C#, VB.NET, ASP) / Programas de broma en: 22 Marzo 2018, 17:29 pm
Hola:

Estaba urgando con C# haciendo archivo de bromas. La idea principal es, que al ejecutar esta aplicación hecha en modo consola, no muestre la pantalla en negro, que no muestre nada, solo que al ejecutarlo tres veces, la primera vez crea un archivo  de texto llamado Archivo.txt que contiene el valor número 3, si llega a 0, crea otro arhivo llamado Hola.txt y en su interior, el contenido escrito esto, Hola amigo.

Los archivos se crean en el escritorio como ejemplo.

Aquí un ejemplo:
Código
  1. using System;
  2. using System.IO;
  3.  
  4. namespace Broma_Consola_02
  5. {
  6.    class Program
  7.    {
  8.        static void Main(string[] args)
  9.        {
  10.            // Variables.
  11.            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  12.            string nombreArchivo = "Archivo.txt";
  13.  
  14.            // Comprueba si existe el archivo en dicha ruta.
  15.            if (File.Exists(Path.Combine(path, nombreArchivo)))
  16.            {
  17.                // Variable del contador.
  18.                int contador;
  19.  
  20.                // Lee el fichero.
  21.                if (Int32.TryParse(File.ReadAllText(Path.Combine(path, nombreArchivo)), out contador))
  22.                {
  23.                    // Si el contador es mayor que 0.
  24.                    if (contador > 0)
  25.                    {
  26.                        // Sobre escribe el archivo con -1 su valor.
  27.                        File.WriteAllText(Path.Combine(path, nombreArchivo), $"{contador -= 1}");
  28.                    }
  29.  
  30.                    // Si el contador es igual a 0.
  31.                    if (contador == 0)
  32.                    {
  33.                        // Escribe un nuevo arhivo de texto con su contenido correspondiente.
  34.                        File.WriteAllText(Path.Combine(path, "Hola.txt"), "Hola amigo.");
  35.                    }
  36.                }
  37.  
  38.                // Entonces.
  39.                else
  40.                {
  41.                    Console.WriteLine("El archivo contiene un valor no esperado.");
  42.                }
  43.            }
  44.  
  45.            // Entonces.
  46.            else
  47.            {
  48.                // Escribe el archivo con el valor 3 en Archivo.txt.
  49.                File.WriteAllText(Path.Combine(path, nombreArchivo), "3");
  50.            }
  51.  
  52.            //Console.ReadKey(); // Pulse cualquier tecla para salir.
  53.        }
  54.    }
  55. }

Mi idea es que este ejecutable esté sea como sea, en el inicio de Windows, es decir, que al iniciar Windows, te resta un valor en el archivo txt hasta llegar a 0. Cuando llegues a 0, al iniciar el Windows, se abre también en el inicio el archivo Hola.txt con el mensaje, Hola amigo.

Aquí abajo lo puse como escritorio, al dinal sustituye Desktop (escritorio)
Código
  1. string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
a Startup (Inicio).
Código
  1. string path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

El que quiere poner otra ubicación, aquí hay una lista.

¿Qué técnica, o ideas, usarían para poder poner este ejecutable en el inicio?

Salu2.
446  Programación / .NET (C#, VB.NET, ASP) / Cambiar atributo archivo en: 11 Marzo 2018, 15:05 pm
Hola:

Tengo este archivo de texto llamado Hola.txt, creado con C#. Sus atributos son estos.


El código para crear este archivo de texto es el siguiente.

Código
  1. using System;
  2. using System.IO; // No olvidar.
  3.  
  4. namespace Crear_txt_Consola_02_cs
  5. {
  6.    class Program
  7.    {
  8.        static void Main(string[] args)
  9.        {
  10.            // Título de la ventana.
  11.            Console.Title = "Crear archivo txt Consola 02 C#";
  12.  
  13.            // Tamaño ventana consola.
  14.            Console.WindowWidth = 55; // X. Ancho.
  15.            Console.WindowHeight = 18; // Y. Alto.
  16.  
  17.            /* Creo que te estás complicando innecesariamente. Si tienes la ruta y el fichero,
  18.              * no hay más que juntar la ruta con el fichero (poniendo la "\" entre medias igual
  19.              * que si fueses a escribir la ruta a mano en el explorador de Windows). Es una simple
  20.              * concatenación de strings:
  21.              */
  22.  
  23.            /*
  24.              string strFileName = @"Hola.txt"; // Nombre del archivo.
  25.              string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Ruta.
  26.              string ficheroAGrabar = ruta + @"\" + strFileName;
  27.             */
  28.  
  29.            // Variables.
  30.            string strFileFullName = @"Hola.txt"; // Nombre del archivo.
  31.            string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Ruta.
  32.            string ficheroAGrabar = Path.Combine(ruta, strFileFullName); // Concatenar ruta.
  33.  
  34.            // Muestra la ruta en pantalla.
  35.            Console.WriteLine(ruta); // C:\Users\Usuario\Desktop
  36.  
  37.            // Si no existe el archivo.
  38.            if (!File.Exists(ficheroAGrabar))
  39.            {
  40.                // Crea el contenido al archivo de texto.
  41.                File.WriteAllText(ficheroAGrabar, "Hola Mundo.");
  42.            }
  43.  
  44.            else // Si existe...
  45.            {
  46.                // Codigo a ejecutar si existe...
  47.                Console.WriteLine("El archivo existe, así que no se sustituirá.");
  48.  
  49.                // Pulse cualquier tecla para salir.
  50.                Console.ReadKey();
  51.            }
  52.        }
  53.    }
  54. }

¿Existe hacer de alguna manera, cambiar los datos de los atributos como fecha y hora indicada en la imagen de arriba?

No quiero que se sepa cuando se creó el archivo. O poner otra fecha muy al pasado.

Saludos.
447  Programación / .NET (C#, VB.NET, ASP) / Re: aprender a programa c# c sharp. en: 11 Marzo 2018, 15:01 pm
Hola mi nombre es insider, y me gustaría aprender a programar en C Sharp, pero no se por donde empezar, soy algo nuevo en este foro,y quisiera que alguien que sea un programador de  de este lenguaje me de algunos consejos, que debo hacer para aprender a programar en el lenguaje c#? que pasos debo tomar?. y si es posible aprender desde Internet?. GRACIAS Y SALUDOS.


· Tema movido C# no es C/C++ es .NET
· No se debe escribir en mayúsculas
>aquí las reglas del foro
-Engel Lex


Empieza viendo estos vídeos con cosas muy básicas.



SAludos.
448  Programación / Scripting / Re: Crear funciones en est script en: 28 Noviembre 2017, 17:13 pm
Lo tendré en cuenta, voy a investigar lo que dices. Gracias. ;)
449  Programación / Scripting / Crear funciones en est script en: 28 Noviembre 2017, 09:57 am
Hola:

Estoy usando desde ISE con PowerShell este código. Lo que hace ahora es crear un formulario Windows Form en el cual abre y cierra la bandeja del lector del disco.

Código:
$MemDef = @"
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
   public static extern int mciSendStringA(
   string lpstrCommand,
   string lpstrReturnString,
   int uReturnLength,
   IntPtr hwndCallback);
"@

$winnm = Add-Type -memberDefinition $MemDef -ErrorAction 'SilentlyContinue' -passthru -name mciSendString
function Set-CDAudioDoor {
 Param(
  [ValidateSet("open", "closed")][String[]]$Mode = 'open'
 )
 $winnm::mciSendStringA("set cdaudio door $mode", $null, 0,0)}

 [void][reflection.assembly]::loadwithpartialname("System.Windows.Forms")
[void][reflection.assembly]::loadwithpartialname("System.Drawing")


$Form = New-Object system.Windows.Forms.Form
$Form.Text = "PowerShell 2017"
$Form.TopMost = $true
$Form.Width = 300
$Form.Height = 300
$Form.StartPosition = "CenterScreen"



$button_Abrir = New-Object system.windows.Forms.Button
$button_Abrir.Text = "Abrir"
$button_Abrir.Width = 75
$button_Abrir.Height = 23
$button_Abrir.location = new-object system.drawing.point(40, 150)
$button_Abrir.Font = "Microsoft Sans Serif,10"
$Form.controls.Add($button_Abrir)


$button_Cerrar = New-Object system.windows.Forms.Button
$button_Cerrar.Text = "Cerrar"
$button_Cerrar.Width = 75
$button_Cerrar.Height = 23
$button_Cerrar.location = new-object system.drawing.point(174, 150)
$button_Cerrar.Font = "Microsoft Sans Serif,10"
$Form.controls.Add($button_Cerrar)




$label_Mensaje = New-Object system.windows.Forms.Label
$label_Mensaje.Text = "?"
$label_Mensaje.AutoSize = $true
$label_Mensaje.Width = 25
$label_Mensaje.Height = 10
$label_Mensaje.location = new-object system.drawing.point(54,26)
$label_Mensaje.Font = "Microsoft Sans Serif,36,style=Bold"
$Form.controls.Add($label_Mensaje)

# Abrir  bandeja.
$label_Mensaje.Text = "Abriendo..."
$button_Abrir.Add_Click({Set-CDAudioDoor open})
$label_Mensaje.Text = "Abierto."

# Cerrar bandeja.
$label_Mensaje.Text = "Cerrando..."
$button_Cerrar.Add_Click({Set-CDAudioDoor closed})
$label_Mensaje.Text = "Cerrado."

[void]$Form.ShowDialog()
$Form.Dispose() 

Al ejecutar este Script, muestra esta imagen.


Com podrás observar, siempre se ejecuta una detrás otra esta instrucción de mensajes.
Código:
$label_Mensaje.Text = "Cerrado."

Mi idea es, que al pulsar el botón Abrir, aparezca el mensaje "Abrriendo...", se abre la bandeja del todo, sale otro mensaje, "Abierto.", lo mismo al pulsar el botón Cerrar.

¿En que fallo?

Saludos.
450  Programación / Programación C/C++ / Re: [SOLUCIONADO] Solucionando errores Menú abrir y cerrar unidad CD-ROM en: 25 Noviembre 2017, 15:13 pm
Se me pasó por alto, ajajjajaja.

Gracias por todo campeón.  ;-)
Páginas: 1 ... 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 [45] 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 ... 255
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines