Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Meta en 22 Marzo 2018, 17:29 pm



Título: Programas de broma
Publicado por: Meta 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 (https://msdn.microsoft.com/es-es/library/system.environment.specialfolder%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396).

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

Salu2.


Título: Re: Programas de broma
Publicado por: Eleкtro en 22 Marzo 2018, 18:43 pm
La creación y manipulación de un archivo de texto plano como "intermediario" es algo primitivo e innecesario (a menos que estuviesemos hablando de un archivo de configuración en formato .ini con sus secciones y sus llaves, que no es el caso). Antes que plantearnos la grotesca idea de manipular archivos de texto plano y sin formato, usarías el registro de Windows para crear un valor y leerlo desde tu aplicación.

En fin, probablemente la solución más cómoda al problema que tienes sencillamente podría ser crear una propiedad de usuario en tu aplicación:

(https://i.imgur.com/CapvhuH.png)

Y trabajar la propiedad de la siguiente manera:

Código
  1. class Program {
  2.  
  3.    static void Main(string[] args) {
  4.  
  5.        int value = Properties.Settings.Default.Countdown;
  6.        Debug.WriteLine("Current value: {0}", value);
  7.  
  8.        switch (value) {
  9.            case 0:
  10.                // ...
  11.                // lo que tengas que hacer aquí cuando el contador llega a 0.
  12.                // ...
  13.                Properties.Settings.Default.Reset(); // Reset Countdown value to 3.
  14.                break;
  15.  
  16.            default: // 1, 2 or 3.
  17.                Properties.Settings.Default.Countdown -= 1;
  18.                break;
  19.        }
  20.  
  21.        Properties.Settings.Default.Save();
  22.        Environment.Exit(0);
  23.    }
  24.  
  25. }

Nota: las propiedades de usuario modificadas se almacenan en el archivo user.config en formato XML, no tienes que preocuparte por administrar nada por ti mismo como harías creando y editando un archivo de texto...



Para ocultar la ventana de la consola sencillamente dirígete a esta pestaña en la configuración del proyecto y modifica el tipo de salida, de Console Aplication a Window Application:

(https://i.imgur.com/Os3GsXQ.png)

...de esta forma, la consola adjunta al programa no se mostrará al inicio.

Nota: una manera alternativa, pero menos amistosa y también menos eficiente de lograr algo similar, sería recurriendo a las funciones de la API de Windows, concretamente a GetConsoleWindow y ShowWindow.



Y por último, para añadir tu programa al inicio de sesión de usuario en Windows, simplemente puedes añadir un nuevo valor de registro en la clave HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run (o en la raíz HKEY_LOCAL_MACHINE para todos los usuarios). Hay otras metodologías alternativas las cuales considero innecesario mencionar... al poder hacerlo de la forma ya explicada.

Hay miles de ejemplos sobre ello en Google para C#, busca un poco. De todas formas aquí te dejo el código fuente de una mini-aplicación que desarrollé (en VB.NET) para ese propósito, el cual puedes analizarlo para obtener las respuestas que necesites...

  • [SOURCE] File 2 startup v1.1 (http://foro.elhacker.net/net/source_file_2_startup_v11-t428089.0.html;msg1989817#msg1989817)

Cita de: File2Startup by Elektro
(http://i.imgur.com/scGFKgD.png)

De nada.

Saludos.


Título: Re: Programas de broma
Publicado por: **Aincrad** en 22 Marzo 2018, 19:17 pm
@Elektro el link del File 2 startup v1.1 esta caido .



la forma en que yo agrego los virus que hago al registro es esta:

Código
  1. Imports Microsoft.Win32
  2.  
  3. Public Class Form1
  4.   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  5.        autoinicio()
  6.        Me.Hide()
  7.    End Sub
  8.  
  9.    Private Sub autoinicio()
  10.        Dim dirPath As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
  11.        If My.Computer.FileSystem.FileExists(dirPath & "pc.exe") Then
  12.            Microsoft_Office_2013.Timer1.Start()
  13.        Else
  14.            My.Computer.FileSystem.CopyFile(Application.ExecutablePath, dirPath & "pc.exe")
  15.            Try
  16.                Dim REGISTRADOR As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", True)
  17.                If REGISTRADOR Is Nothing Then
  18.                    Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run")
  19.                End If
  20.                Dim NOMBRE As String = dirPath & "pc.exe"
  21.                NOMBRE = NOMBRE.Remove(0, NOMBRE.LastIndexOf("\") + 1)
  22.                REGISTRADOR.SetValue(NOMBRE, dirPath & "pc.exe", RegistryValueKind.String)
  23.                Microsoft_Office_2013.Show()
  24.            Catch ex As Exception
  25.                Dim Result As DialogResult = MessageBox.Show(ex.Message, "Error as ocurrent", MessageBoxButtons.OK, MessageBoxIcon.Error)
  26.                If Result = DialogResult.OK Then
  27.                    End
  28.                End If
  29.            End Try
  30.        End If
  31.     End Sub
  32. End Class

PD: Es una pequeña parte del virus de mause que publique hace unas semanas en la parte de Análisis y Diseño de Malware


Título: Re: Programas de broma
Publicado por: Serapis en 22 Marzo 2018, 21:15 pm
la forma en que yo agrego los virus que hago al registro es esta:

            Microsoft_Office_2013.Timer1.Start()
mmm... Supongamos que yo no tengo instalado Office 2013...

Usa soluciones genéricas, no dependientes de si tienes instalado tal o cual cosa.


Título: Re: Programas de broma
Publicado por: Eleкtro en 22 Marzo 2018, 21:32 pm
@Elektro el link del File 2 startup v1.1 esta caido .

Gracias por el aviso. Ya está actualizado y resubido... esta vez a GitHub:

(http://www.factor.io/images/hero-open-in-github-white.png) (https://github.com/ElektroStudios/File2Startup/releases/latest)

Nota: se me olvidó actualizar la versión en las propiedades del ensamblado, así que se mostrará 1.1.0.0, pero es la versión 1.2.0.0. No hay cambios importantes en el programa, de hecho el único cambio ha sido reemplazar y adaptar todas las clases del código fuente original (del año 2015), por las clases y miembros que utilizo hoy por hoy en el código fuente de la librería comercial ElektroKit, que se proporcionan de forma muy reducida pero gratuita en este repositorio...



Por cierto, ya no recordaba que también desarrollé esto en el pasado, lo cual simplifica mucho la tarea...

  • Re: Librería de Snippets !! (Compartan aquí sus snippets) (https://foro.elhacker.net/net/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg2004808#msg2004808)

Cita de: https://foro.elhacker.net/net/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg2004808#msg2004808
Este snippet sirve para añadir o eliminar de forma muuuuuy sencilla :P un archivo/aplicación al Startup de Windows mediante el registro, con características interesantes...

Modo de empleo:
Código
  1. WinStartupUtil.Add(UserType.CurrentUser, StartupType.Run, KeyBehavior.System32,
  2.                   title:="Application Title",
  3.                   filePath:="C:\Application.exe",
  4.                   arguments:="/Arguments",
  5.                   secureModeByPass:=True)

Código
  1. WinStartupUtil.Remove(UserType.CurrentUser, StartupType.Run, KeyBehavior.System32,
  2.                      title:="Application Title",
  3.                      throwOnMissingValue:=True)


Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 25-March-2015
  4. ' ***********************************************************************
  5. ' <copyright file="WinStartupUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'WinStartupUtil.Add(WinStartupUtil.UserType.CurrentUser,
  13. '                   WinStartupUtil.StartupType.Run,
  14. '                   WinStartupUtil.KeyBehavior.System32,
  15. '                   title:="Application Title",
  16. '                   filePath:="C:\Application.exe",
  17. '                   secureModeByPass:=True)
  18.  
  19. 'WinStartupUtil.Remove(WinStartupUtil.UserType.CurrentUser,
  20. '                      WinStartupUtil.StartupType.Run,
  21. '                      WinStartupUtil.KeyBehavior.System32,
  22. '                      title:="Application Title",
  23. '                      throwOnMissingValue:=True)
  24.  
  25. #End Region
  26.  
  27. #Region " Option Statements "
  28.  
  29. Option Explicit On
  30. Option Strict On
  31. Option Infer Off
  32.  
  33. #End Region
  34.  
  35. #Region " Imports "
  36.  
  37. Imports Microsoft.Win32
  38.  
  39. #End Region
  40.  
  41. #Region " WinStartupUtil "
  42.  
  43.  
  44. ''' <summary>
  45. ''' Adds or removes an application to Windows Startup.
  46. ''' </summary>
  47. Public NotInheritable Class WinStartupUtil
  48.  
  49. #Region " Properties "
  50.  
  51.    ''' <summary>
  52.    ''' Gets the 'Run' registry subkey path.
  53.    ''' </summary>
  54.    ''' <value>The 'Run' registry subkey path.</value>
  55.    Public Shared ReadOnly Property RunSubKeyPath As String
  56.        Get
  57.            Return "Software\Microsoft\Windows\CurrentVersion\Run"
  58.        End Get
  59.    End Property
  60.  
  61.    ''' <summary>
  62.    ''' Gets the 'Run' registry subkey path for x86 appications on x64 operating system.
  63.    ''' </summary>
  64.    ''' <value>The 'Run' registry subkey path for x86 appications on x64 operating system.</value>
  65.    Public Shared ReadOnly Property RunSubKeyPathSysWow64 As String
  66.        Get
  67.            Return "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"
  68.        End Get
  69.    End Property
  70.  
  71.    ''' <summary>
  72.    ''' Gets the 'RunOnce' registry subkey path.
  73.    ''' </summary>
  74.    ''' <value>The 'RunOnce' registry subkey path.</value>
  75.    Public Shared ReadOnly Property RunOnceSubKeyPath As String
  76.        Get
  77.            Return "Software\Microsoft\Windows\CurrentVersion\RunOnce"
  78.        End Get
  79.    End Property
  80.  
  81.    ''' <summary>
  82.    ''' Gets the 'RunOnce' registry subkey path for x86 appications on x64 operating system.
  83.    ''' </summary>
  84.    ''' <value>The 'RunOnce' registry subkey path for x86 appications on x64 operating system.</value>
  85.    Public Shared ReadOnly Property RunOnceSubKeyPathSysWow64 As String
  86.        Get
  87.            Return "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce"
  88.        End Get
  89.    End Property
  90.  
  91. #End Region
  92.  
  93. #Region " Enumerations "
  94.  
  95.    ''' <summary>
  96.    ''' Specifies an user type.
  97.    ''' </summary>
  98.    Public Enum UserType As Integer
  99.  
  100.        ''' <summary>
  101.        ''' 'HKEY_CURRENT_USER' root key.
  102.        ''' </summary>
  103.        CurrentUser = &H1
  104.  
  105.        ''' <summary>
  106.        ''' 'HKEY_LOCAL_MACHINE' root key.
  107.        ''' </summary>
  108.        AllUsers = &H2
  109.  
  110.    End Enum
  111.  
  112.    ''' <summary>
  113.    ''' Specifies a Startup type.
  114.    ''' </summary>
  115.    Public Enum StartupType As Integer
  116.  
  117.        ''' <summary>
  118.        ''' 'Run' registry subkey.
  119.        ''' </summary>
  120.        Run = &H1
  121.  
  122.        ''' <summary>
  123.        ''' 'RunOnce' registry subkey.
  124.        ''' </summary>
  125.        RunOnce = &H2
  126.  
  127.    End Enum
  128.  
  129.    ''' <summary>
  130.    ''' Specifies a registry key behavior.
  131.    ''' </summary>
  132.    Public Enum KeyBehavior As Integer
  133.  
  134.        ''' <summary>
  135.        ''' System32 registry subkey.
  136.        ''' </summary>
  137.        System32 = &H1
  138.  
  139.        ''' <summary>
  140.        ''' SysWow64 registry subkey.
  141.        ''' </summary>
  142.        SysWow64 = &H2
  143.  
  144.    End Enum
  145.  
  146. #End Region
  147.  
  148. #Region " Public Methods "
  149.  
  150.    ''' <summary>
  151.    ''' Adds an application to Windows Startup.
  152.    ''' </summary>
  153.    ''' <param name="userType">The type of user.</param>
  154.    ''' <param name="startupType">The type of startup.</param>
  155.    ''' <param name="keyBehavior">The registry key behavior.</param>
  156.    ''' <param name="title">The registry value title.</param>
  157.    ''' <param name="filePath">The application file path.</param>
  158.    ''' <param name="secureModeByPass">
  159.    ''' If set to <c>true</c>, the file is ran even when the user logs into 'Secure Mode' on Windows.
  160.    ''' </param>
  161.    ''' <exception cref="System.ArgumentNullException">title or filePath</exception>
  162.    Public Shared Sub Add(ByVal userType As UserType,
  163.                          ByVal startupType As StartupType,
  164.                          ByVal keyBehavior As KeyBehavior,
  165.                          ByVal title As String,
  166.                          ByVal filePath As String,
  167.                          Optional ByVal arguments As String = "",
  168.                          Optional secureModeByPass As Boolean = False)
  169.  
  170.        If String.IsNullOrEmpty(title) Then
  171.            Throw New ArgumentNullException("title")
  172.  
  173.        ElseIf String.IsNullOrEmpty(filePath) Then
  174.            Throw New ArgumentNullException("filePath")
  175.  
  176.        Else
  177.            If secureModeByPass Then
  178.                title = title.Insert(0, "*")
  179.            End If
  180.  
  181.            Dim regKey As RegistryKey = Nothing
  182.            Try
  183.                regKey = GetRootKey(userType).OpenSubKey(GetSubKeyPath(startupType, keyBehavior), writable:=True)
  184.                regKey.SetValue(title, String.Format("""{0}"" {1}", filePath, arguments), RegistryValueKind.String)
  185.  
  186.            Catch ex As Exception
  187.                Throw
  188.  
  189.            Finally
  190.                If regKey IsNot Nothing Then
  191.                    regKey.Close()
  192.                End If
  193.  
  194.            End Try
  195.  
  196.        End If
  197.  
  198.    End Sub
  199.  
  200.    ''' <summary>
  201.    ''' Removes an application from Windows Startup.
  202.    ''' </summary>
  203.    ''' <param name="userType">The type of user.</param>
  204.    ''' <param name="startupType">The type of startup.</param>
  205.    ''' <param name="keyBehavior">The registry key behavior.</param>
  206.    ''' <param name="title">The value name to find.</param>
  207.    ''' <param name="throwOnMissingValue">if set to <c>true</c>, throws an exception on missing value.</param>
  208.    ''' <exception cref="System.ArgumentNullException">title</exception>
  209.    ''' <exception cref="System.ArgumentException">Registry value not found.;title</exception>
  210.    Friend Shared Sub Remove(ByVal userType As UserType,
  211.                             ByVal startupType As StartupType,
  212.                             ByVal keyBehavior As KeyBehavior,
  213.                             ByVal title As String,
  214.                             Optional ByVal throwOnMissingValue As Boolean = False)
  215.  
  216.        If String.IsNullOrEmpty(title) Then
  217.            Throw New ArgumentNullException("title")
  218.  
  219.        Else
  220.            Dim valueName As String = String.Empty
  221.            Dim regKey As RegistryKey = Nothing
  222.  
  223.            Try
  224.                regKey = GetRootKey(userType).OpenSubKey(GetSubKeyPath(startupType, keyBehavior), writable:=True)
  225.  
  226.                If regKey.GetValue(title, defaultValue:=Nothing) IsNot Nothing Then
  227.                    valueName = title
  228.  
  229.                ElseIf regKey.GetValue(title.Insert(0, "*"), defaultValue:=Nothing) IsNot Nothing Then
  230.                    valueName = title.Insert(0, "*")
  231.  
  232.                Else
  233.                    If throwOnMissingValue Then
  234.                        Throw New ArgumentException("Registry value not found.", "title")
  235.                    End If
  236.  
  237.                End If
  238.  
  239.                regKey.DeleteValue(valueName, throwOnMissingValue:=throwOnMissingValue)
  240.  
  241.            Catch ex As Exception
  242.                Throw
  243.  
  244.            Finally
  245.                If regKey IsNot Nothing Then
  246.                    regKey.Close()
  247.                End If
  248.  
  249.            End Try
  250.  
  251.        End If
  252.  
  253.    End Sub
  254.  
  255. #End Region
  256.  
  257. #Region " Private Methods "
  258.  
  259.    ''' <summary>
  260.    ''' Gets a <see cref="RegistryKey"/> instance of the specified root key.
  261.    ''' </summary>
  262.    ''' <param name="userType">The type of user.</param>
  263.    ''' <returns>A <see cref="RegistryKey"/> instance of the specified root key.</returns>
  264.    ''' <exception cref="System.ArgumentException">Invalid enumeration value.;userType</exception>
  265.    Private Shared Function GetRootKey(ByVal userType As UserType) As RegistryKey
  266.  
  267.        Select Case userType
  268.  
  269.            Case userType.CurrentUser
  270.                Return Registry.CurrentUser
  271.  
  272.            Case userType.AllUsers
  273.                Return Registry.LocalMachine
  274.  
  275.            Case Else
  276.                Throw New ArgumentException("Invalid enumeration value.", "userType")
  277.  
  278.        End Select ' userType
  279.  
  280.    End Function
  281.  
  282.    ''' <summary>
  283.    ''' Gets the proper registry subkey path from the parameters criteria.
  284.    ''' </summary>
  285.    ''' <param name="startupType">Type of the startup.</param>
  286.    ''' <param name="keyBehavior">The key behavior.</param>
  287.    ''' <returns>The registry subkey path.</returns>
  288.    ''' <exception cref="System.ArgumentException">
  289.    ''' Invalid enumeration value.;startupType or
  290.    ''' Invalid enumeration value.;keyBehavior
  291.    ''' </exception>
  292.    Private Shared Function GetSubKeyPath(ByVal startupType As StartupType,
  293.                                          ByVal keyBehavior As KeyBehavior) As String
  294.  
  295.        Select Case keyBehavior
  296.  
  297.            Case keyBehavior.System32
  298.  
  299.                Select Case startupType
  300.  
  301.                    Case startupType.Run
  302.                        Return RunSubKeyPath
  303.  
  304.                    Case startupType.RunOnce
  305.                        Return RunOnceSubKeyPath
  306.  
  307.                    Case Else
  308.                        Throw New ArgumentException("Invalid enumeration value.", "startupType")
  309.  
  310.                End Select ' startupType
  311.  
  312.            Case keyBehavior.SysWow64
  313.  
  314.                Select Case startupType
  315.  
  316.                    Case startupType.Run
  317.                        Return RunSubKeyPathSysWow64
  318.  
  319.                    Case startupType.RunOnce
  320.                        Return RunOnceSubKeyPathSysWow64
  321.  
  322.                    Case Else
  323.                        Throw New ArgumentException("Invalid enumeration value.", "startupType")
  324.  
  325.                End Select ' startupType
  326.  
  327.            Case Else
  328.                Throw New ArgumentException("Invalid enumeration value.", "keyBehavior")
  329.  
  330.        End Select ' keyBehavior
  331.  
  332.    End Function
  333.  
  334. #End Region
  335.  
  336. End Class
  337.  
  338. #End Region

Saludos!


Título: Re: Programas de broma
Publicado por: Meta 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 (https://foro.elhacker.net/net/source_file_2_startup_v11-t428089.0.html;msg1989817#msg1989817).

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

Saludos..


Título: Re: Programas de broma
Publicado por: Meta 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.


Título: Re: Programas de broma
Publicado por: Meta en 5 Abril 2018, 04:29 am
Hola:

¿Qué les parece la broma?
Todavía queda mucho que pulir, poco a poco se va ampliando y mejorando.

Leer los comentarios para entender el código.

Código
  1. using Microsoft.Win32;
  2. using System;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Drawing.Printing;
  7. using System.IO;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Threading;
  11.  
  12. namespace Broma_Consola_05
  13. {
  14.    class Program
  15.    {
  16.        // Importar dll.
  17.        // Bandeja o lector o unidad de disco.
  18.        [DllImport("winmm.dll")]
  19.        public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
  20.        int uReturnLength, IntPtr hwndCallback);
  21.  
  22.        public static StringBuilder rt = new StringBuilder(127);
  23.  
  24.        // Intercambio de botones del ratón.
  25.        [DllImport("user32.dll")]
  26.        static extern bool SwapMouseButton(bool fSwap);
  27.  
  28.        // Leds del teclado.
  29.        [DllImport("user32.dll")]
  30.        internal static extern short GetKeyState(int keyCode);
  31.  
  32.        [DllImport("user32.dll")]
  33.        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
  34.  
  35.        static void Main(string[] args)
  36.        {
  37.            // Root.
  38.            const string userRoot = "HKEY_CURRENT_USER";
  39.            // Clave.
  40.            const string subkey = "Metaconta";
  41.            // FullName.
  42.            const string keyName = userRoot + "\\" + subkey;
  43.            // ValueName.
  44.            const string valueName = "Contador";
  45.  
  46.            // Variables txt.
  47.            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  48.  
  49.            // Si no existe la Key, dará -1.
  50.            int contador = Convert.ToInt32(Registry.GetValue(keyName, valueName, -1) ?? -1);
  51.  
  52.            // Comprueba si la key, al ser -1 si la key no existe.
  53.            if (contador >= 0)
  54.            {
  55.                // Si el contador es mayor que 0.
  56.                if (contador > 0)
  57.                {
  58.                    // Sobre escribe la key con -1 su valor.
  59.                    Registry.SetValue(keyName, valueName, contador -= 1);
  60.                }
  61.  
  62.                // Escribe un nuevo arhivo de texto con su contenido correspondiente.
  63.                if (contador == 7)
  64.                {
  65.                    File.WriteAllText(Path.Combine(path, "Hola.txt"), "Hola amigo.");
  66.                }
  67.  
  68.                // Abrir bandeja del lector.
  69.                if (contador == 6)
  70.                {
  71.                    mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
  72.                }
  73.  
  74.                // Intercambiar botones del ratón (Diestro).
  75.                if (contador == 5)
  76.                {
  77.                    SwapMouseButton(false); // Activar .
  78.                }
  79.  
  80.                // Intercambiar botones del ratón (Zurdo).
  81.                if (contador == 4)
  82.                {
  83.                    // Activar modo zurdo.
  84.                    // SwapMouseButton(true); o SwapMouseButton(1);
  85.                    // Para volver a modo diestro.
  86.                    // SwapMouseButton(false); o SwapMouseButton(0);
  87.                    SwapMouseButton(true); // Activar surdo.
  88.                }
  89.  
  90.                // Imprimir un folio de la impresora o ficticia.
  91.                if (contador == 3)
  92.                {
  93.                    string amigo = @"Hola amigo.";
  94.                    string folio = @"Solo te he gastado un folio.";
  95.  
  96.                    PrintDocument p = new PrintDocument();
  97.                    p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
  98.                    {
  99.                        e1.Graphics.DrawString(amigo, new Font("Times New Roman", 100),
  100.                            new SolidBrush(Color.Black), new RectangleF(30, 100,
  101.                            p.DefaultPageSettings.PrintableArea.Width,
  102.                            p.DefaultPageSettings.PrintableArea.Height));
  103.  
  104.                        e1.Graphics.DrawString(folio, new Font("Times New Roman", 12),
  105.                            new SolidBrush(Color.Black), new RectangleF(530, 270,
  106.                            p.DefaultPageSettings.PrintableArea.Width,
  107.                            p.DefaultPageSettings.PrintableArea.Height));
  108.                    };
  109.  
  110.                    try
  111.                    {
  112.                        p.Print();
  113.                    }
  114.                    catch (Exception ex)
  115.                    {
  116.                        throw new Exception("Excepción ocurrida durante la impresión.", ex);
  117.                    }
  118.                }
  119.  
  120.                // Parpadean los Led del teclado.
  121.                if (contador == 2)
  122.                {
  123.                    while (true)
  124.                    {
  125.                        //No se el orden porque no tengo un teclado mecanico para ver los 3 pilotos juntos
  126.                        PressKeyboardButton(VirtualKeyStates.BloqMayus);
  127.                        Thread.Sleep(100); //Ajusta estos tiempos a como te interese
  128.                        PressKeyboardButton(VirtualKeyStates.BloqNum);
  129.                        Thread.Sleep(100);
  130.                        PressKeyboardButton(VirtualKeyStates.BloqDespl);
  131.                        Thread.Sleep(100);
  132.                    }
  133.  
  134.                    void PressKeyboardButton(VirtualKeyStates keyCode)
  135.                    {
  136.                        const int KEYEVENTF_EXTENDEDKEY = 0x1;
  137.                        const int KEYEVENTF_KEYUP = 0x2;
  138.                        keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
  139.                        keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
  140.                    }
  141.                }
  142.  
  143.                // Crea archivo bat, borra .exe y .cmd. Fin de la broma.
  144.                if (contador == 1)
  145.                {
  146.                    try
  147.                    {
  148.                        // Variables.
  149.                        string strFileFullName = @"archivo.cmd"; // Nombre del archivo.
  150.                                                                 //string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Ruta en Inico de Windwos.
  151.                        string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Ruta en el inicio de Windows.
  152.                        string ficheroAGrabar = Path.Combine(ruta, strFileFullName); // Concatenar ruta.
  153.  
  154.                        // Muestra la ruta en pantalla.
  155.                        Console.WriteLine(ruta); // C:\Users\Usuario\Desktop
  156.  
  157.                        // Si no existe el archivo.
  158.                        if (!File.Exists(ficheroAGrabar))
  159.                        {
  160.                            // Crea el contenido al archivo de texto.
  161.                            File.WriteAllText(ficheroAGrabar, @"@echo off
  162. TIMEOUT /T 1
  163. DEL /S Broma_Consola_05.exe
  164. DEL /S archivo.cmd
  165. EXIT");
  166.                        }
  167.  
  168.                        else // Si existe...
  169.                        {
  170.                            // Codigo a ejecutar si existe...
  171.                            // Console.WriteLine("El archivo existe, así que no se sustituirá.");
  172.                        }
  173.  
  174.                        // Ejecutar archivo.cmd.
  175.                        ProcessStartInfo psi = new ProcessStartInfo();
  176.                        psi.UseShellExecute = false;
  177.                        psi.CreateNoWindow = true;
  178.                        psi.WindowStyle = ProcessWindowStyle.Hidden;
  179.                        psi.FileName = strFileFullName; // archivo.cmd.
  180.                        Process.Start(psi);
  181.  
  182.                        // Cerrar aplicación C#.
  183.                        Environment.Exit(-1);
  184.                    }
  185.  
  186.                    catch (Win32Exception)
  187.                    {
  188.                        // No mostrar nada.
  189.                        // Cerrar aplicación C#.
  190.                        //Environment.Exit(-1);
  191.                    }
  192.                }
  193.                // Entonces.
  194.                else
  195.                {
  196.                    // Escribe en el registro el valor.
  197.                    Registry.SetValue(keyName, valueName, 10);
  198.                }
  199.            }
  200.        }
  201.  
  202.        public enum VirtualKeyStates : int
  203.        {
  204.            BloqMayus = 0x14, // 20
  205.            BloqNum = 0x90, //144
  206.            BloqDespl = 0x91, //145  
  207.        }
  208.    }
  209. }
  210.  

Saludos.


Título: Re: Programas de broma
Publicado por: Meta en 17 Abril 2018, 02:41 am
Buenas:

Siguiendo la broma. Ahora está la parte de invertir la pantalla, cuando vuelvas a iniciar, se vuelve normal.

El problema que me di cuenta en Windows 10, pueden saber que en inicio hay un programa.

(https://www.subeimagenes.com/img/captura-1858028.PNG)

¿No hay otro sitio para esconderlo?

Tendré que usar trucos como , usar el icono de Java. Donde pone anunciante, poner su anuncio. Como pueden ver en Broma_Consola_06, no tiene nada en Anunciante.

¿Cómo se pone algo?

Saludos.


Título: Re: Programas de broma
Publicado por: Eleкtro en 17 Abril 2018, 04:01 am
usar el icono de Java.

Eso ya más que broma estaría rozando el ser considerado software malicioso...

Donde pone anunciante, poner su anuncio. Como pueden ver en Broma_Consola_06, no tiene nada en Anunciante.

¿Cómo se pone algo?

(https://i.imgur.com/4KLbj3I.png)

Saludos...


Título: Re: Programas de broma
Publicado por: Meta en 17 Abril 2018, 11:49 am
Buenas:

No es malicioso ni la rosa. Me he informado bien por Internet. Es broma, peligrosos si infecta, se propaga mientras hace daño por donde pase. En este caso, al final que sigo con la broma, tiene que estar el ordenador en buen estado, tal como lo encontró al principio. Sin pérdidas de datos, sin robo de contraseñas de Web o lo que sea, sin cosas maliciosas. ;)

Ya pondré el programa final cuando lo acabe.

Para escapar, a lo mejor lo pongo en modo servicios para que no se den cuenta. Aquí leyendo un poco el tutorial (https://docs.microsoft.com/es-es/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer) haber como es.

Gracias por la información.


Título: Re: Programas de broma
Publicado por: Eleкtro en 17 Abril 2018, 11:56 am
No es malicioso ni la rosa. Me he informado bien por Internet. Es broma, peligrosos si infecta

Has manifestado la intención de suplantar la identidad de un proceso legítimo de confianza para los usuarios como es el cliente de Java, usar su mismo icono y la misma información de versión de archivo (aquello de "Anunciante") para camuflarte y parecer el proceso de Java, para volver tu proceso "indetectable" (entre comillas), vaya.

No dije que el código de tu programa fuese malicioso, dije que al hacer eso estarías rozando una delgada linea entre lo que se puede considerar una broma y lo que se puede considerar software malicioso. Por ese motivo y en mi humilde opinión no deberías hacer eso, piensalo detenidamente, será por la infinidad de otros iconos que puedes usar y las millones de ideas que se te pueden ocurrir para escribir la información de archivo de tu programa...

Saludos!


Título: Re: Programas de broma
Publicado por: Serapis en 17 Abril 2018, 14:57 pm
Un programa es malicioso, desde el mismo momento en que hace algo que el usuario no ha aprobado...

...es malicioso, además, porque cuando empiece a hacer esas cosas, el usuario puede pensar que está infectado con un virus y debido a ello, puede entrarle prisas por formatear, o intentar cualquier tontería, lo que como mínimo hace malfastar su tiempo y en lo peor, puede perter el contenido completo del disco duro, si no tiene conocimientos suficientes...


Título: Re: Programas de broma
Publicado por: Meta en 18 Abril 2018, 10:36 am
Buenas:

Parece ser que es una broma pesada. En cuanto al icono de Java, nombré eso pro nombrar, puede ser otro. Hay muchos iconos por internet. Hay que intentar una cosa que lo primero que se le ocurra, es no formatear así sin más.

Hay una broma que le llegó a un amigo, salió una barra de formateando disco duro y haciendo mucho ruido. Al final salió un mensaje en castellano que dijo:

Citar
Es una broma.
A la próxima ten mucho cuidado con los archivos que ejectutes.

Mi broma continua cuando al final de repente, aparezca la famosa pantalla azul sobre error de Windows, un segundo o dos, para que no le de tiempo a reiniciar ya, como hacen muchos, al final dirá letra por letra.

Citar
Es una broma.

Se quita la pantalla.

El ordenador del cliente tiene que estar intacto, como si no hubiera ocurrido nada, sano y salvo. Sin infecciones, sin modificaciones, sin huellas en el regedit, como el nombre el ejecutable que se queda guardado ahí, y sin ninguna otra majadería. el ejecutable debe desaparecer, sea desde el inico o en servivios, que es lo que estoy haciendo pruebas ahora mismo para conocerlo a fondo, nada de conectarse a internet, nada de robos de datos o información del usuario como saber que PC usa, aquí solo bromas, sin causar grandes molestias o sustos graves. Por ahora, no lo detecta ningún antivirus.

;)


Título: Re: Programas de broma
Publicado por: **Aincrad** en 20 Abril 2018, 16:40 pm
No as intentado usar un rootkit ?

Rootkit Startup Method ( full hidden startup x32 x86 working ) vb.net  ;D

Vko4cdNCCT8



Título: Re: Programas de broma
Publicado por: Meta en 21 Abril 2018, 19:23 pm
No as intentado usar un rootkit ?

Rootkit Startup Method ( full hidden startup x32 x86 working ) vb.net  ;D

Vko4cdNCCT8



Sí.

Muchísimo.

Por ahora centrado en hacer el programa principal. A parte de eso, estaba aprendiendo también manejar servicios windows que es un rollo que no veas para lo que quiero.

Intentaré seguir la tónica de Visual Basic .net centrado a C#. Todavía no se desprenden del VB 6 ni loco.

La razón por la cual Microsoft descontinuó Visual Basic (https://velneo.es/por-que-microsoft-descontinuo-visual-basic/).

Gracias por el videazo. ;)


Título: Re: Programas de broma
Publicado por: Maurice_Lupin en 26 Abril 2018, 18:06 pm
Ya que no será malicioso puedes inyectar tu código en otro proceso que sea común... :D tiempo que no toco el formato PE.

Por ejemplo en vb
http://www.forosdelweb.com/f69/inyectar-exe-otro-exe-670787/

Veo que usas funciones de la API, bien podrías hacerlo en C/C++ así tu broma no dependerá del netframework.

Saludos.


Título: Re: Programas de broma
Publicado por: Meta en 3 Mayo 2018, 23:44 pm
Ya que no será malicioso puedes inyectar tu código en otro proceso que sea común... :D tiempo que no toco el formato PE.

Por ejemplo en vb
http://www.forosdelweb.com/f69/inyectar-exe-otro-exe-670787/

Veo que usas funciones de la API, bien podrías hacerlo en C/C++ así tu broma no dependerá del netframework.

Saludos.

Gracias por la info caballero, pero no entiendo esto por ahora. Me centro primero en lo que estoy haciendo y luego observo lo que cuentas. Haber que ventajas tiene.

Por ahora he hecho esto.
Código
  1. using Microsoft.Win32;
  2. using System;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Drawing; // A&#241;adir referencia.
  6. using System.Drawing.Printing;
  7. using System.IO;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Threading;
  11.  
  12. namespace Broma_Consola_06
  13. {
  14.    class Program
  15.    {
  16.        // Importar dll.
  17.        // Bandeja o lector o unidad de disco.
  18.        [DllImport("winmm.dll")]
  19.        public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
  20.        int uReturnLength, IntPtr hwndCallback);
  21.  
  22.        public static StringBuilder rt = new StringBuilder(127);
  23.  
  24.        // Intercambio de botones del rat&#243;n.
  25.        [DllImport("user32.dll")]
  26.        static extern bool SwapMouseButton(bool fSwap);
  27.  
  28.        // Leds del teclado.
  29.        [DllImport("user32.dll")]
  30.        internal static extern short GetKeyState(int keyCode);
  31.  
  32.        [DllImport("user32.dll")]
  33.        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
  34.  
  35.        // Giro pantalla.
  36.        #region Giro pantalla.
  37.        public static class NativeMethods
  38.        {
  39.            // Declaraci&#243;n PInvoke para poder llamar al m&#233;todo EnumDisplaySettings de la API Win32.
  40.            // Recupera los modos de visualizaci&#243;n disponibles.
  41.            [DllImport("user32.dll", CharSet = CharSet.Ansi)]
  42.            private static extern int EnumDisplaySettings(
  43.                string lpszDeviceName,
  44.                int iModeNum,
  45.                ref DEVMODE lpDevMode);
  46.  
  47.            // Declaraci&#243;n PInvoke para poder llamar al m&#233;todo ChangeDisplaySettings de la API Win32.
  48.            // Cambia el modo de visualizaci&#243;n actual.
  49.            [DllImport("user32.dll", CharSet = CharSet.Ansi)]
  50.            public static extern int ChangeDisplaySettings(
  51.                ref DEVMODE lpDevMode,
  52.                int dwFlags);
  53.  
  54.            // Crea un objeto DEVMODE con la informaci&#243;n del modo de visualizaci&#243;n.
  55.            public static DEVMODE CreateDevMode()
  56.            {
  57.                int ENUM_CURRENT_SETTINGS = -1;
  58.                DEVMODE dm = new DEVMODE
  59.                {
  60.                    dmDeviceName = new string(new char[32]),
  61.                    dmFormName = new string(new char[32])
  62.                };
  63.                dm.dmSize = (short)Marshal.SizeOf(dm);
  64.                EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref dm);
  65.                return dm;
  66.            }
  67.  
  68.  
  69.            // Constantes.
  70.            // Modos de visualizaci&#243;n (girado 0/90/180/270 grados).
  71.            public const int DMDO_DEFAULT = 0;
  72.            public const int DMDO_90 = 1;
  73.            public const int DMDO_180 = 2;
  74.            public const int DMDO_270 = 3;
  75.        }
  76.  
  77.        // Mapear la estructura que define el modo de visualizaci&#243;n en user32.dll.
  78.        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  79.        public struct DEVMODE
  80.        {
  81.            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName;
  82.  
  83.            public readonly short dmSpecVersion;
  84.            public short dmDriverVersion;
  85.            public short dmSize;
  86.            public short dmDriverExtra;
  87.            public int dmFields;
  88.            public int dmPositionX;
  89.            public int dmPositionY;
  90.            public int dmDisplayOrientation;
  91.            public int dmDisplayFixedOutput;
  92.            public short dmColor;
  93.            public short dmDuplex;
  94.            public short dmYResolution;
  95.            public short dmTTOption;
  96.            public short dmCollate;
  97.  
  98.            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName;
  99.  
  100.            public short dmLogPixels;
  101.            public short dmBitsPerPel;
  102.            public int dmPelsWidth;
  103.            public int dmPelsHeight;
  104.            public int dmDisplayFlags;
  105.            public int dmDisplayFrequency;
  106.            public int dmICMMethod;
  107.            public int dmICMIntent;
  108.            public int dmMediaType;
  109.            public int dmDitherType;
  110.            public int dmReserved1;
  111.            public int dmReserved2;
  112.            public int dmPanningWidth;
  113.            public int dmPanningHeight;
  114.        }
  115.  
  116.        private static void Swap()
  117.        {
  118.            // Creamos el objeto DEVMODE con la informaci&#243;n del modo de visualizaci&#243;n.
  119.            var dm = NativeMethods.CreateDevMode();
  120.  
  121.            // Establecemos la orientaci&#243;n en funci&#243;n de la actual (girando 180&#186;)
  122.            // a trav&#233;s de la propiedad dmDisplayOrientation.
  123.            var previousDisplayOrientation = dm.dmDisplayOrientation;
  124.            switch (previousDisplayOrientation)
  125.            {
  126.                case NativeMethods.DMDO_DEFAULT:
  127.                    dm.dmDisplayOrientation = NativeMethods.DMDO_180;
  128.                    break;
  129.                case NativeMethods.DMDO_270:
  130.                    dm.dmDisplayOrientation = NativeMethods.DMDO_90;
  131.                    break;
  132.                case NativeMethods.DMDO_180:
  133.                    dm.dmDisplayOrientation = NativeMethods.DMDO_DEFAULT;
  134.                    break;
  135.                case NativeMethods.DMDO_90:
  136.                    dm.dmDisplayOrientation = NativeMethods.DMDO_270;
  137.                    break;
  138.            }
  139.            // Cambia la pantalla al nuevo modo de visualizaci&#243;n.
  140.            //NativeMethods.ChangeDisplaySettings(ref dm, 0);
  141.            NativeMethods.ChangeDisplaySettings(ref dm, 0);
  142.  
  143.            //// A los dos segundos recupera su estado normal.
  144.            //Task.Delay(2000).ContinueWith(t =>
  145.            //{
  146.            //    // Restablece la orientaci&#243;n previa.
  147.            //    dm.dmDisplayOrientation = previousDisplayOrientation;
  148.            //    // Cambia la pantalla al modo anterior.
  149.            //    NativeMethods.ChangeDisplaySettings(ref dm, 0);
  150.            //});
  151.        }
  152.        #endregion
  153.  
  154.        static void Main(string[] args)
  155.        {
  156.            // Root.
  157.            const string userRoot = "HKEY_CURRENT_USER";
  158.            // Clave.
  159.            const string subkey = "Metaconta";
  160.            // FullName.
  161.            const string keyName = userRoot + "\\" + subkey;
  162.            // ValueName.
  163.            const string valueName = "Contador";
  164.  
  165.            // Variables txt.
  166.            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  167.  
  168.            // Si no existe la Key, dar&#225; -1.
  169.            int contador = Convert.ToInt32(Registry.GetValue(keyName, valueName, -1) ?? -1);
  170.  
  171.            bool led = true;
  172.  
  173.            // Comprueba si la key, al ser -1 si la key no existe.
  174.            if (contador >= 0)
  175.            {
  176.                // Si el contador es mayor que 0.
  177.                if (contador > 0)
  178.                {
  179.                    // Sobre escribe la key con -1 su valor.
  180.                    Registry.SetValue(keyName, valueName, contador -= 1);
  181.                }
  182.  
  183.                // Cambio giro pantalla a 180&#186;.
  184.                if (contador == 9)
  185.                {
  186.                    Swap();
  187.                }
  188.  
  189.                if (contador == 8)
  190.                {
  191.                    Swap();
  192.                }
  193.  
  194.                // Escribe un nuevo arhivo de texto con su contenido correspondiente.
  195.                if (contador == 7)
  196.                {
  197.                    File.WriteAllText(Path.Combine(path, "Hola.txt"), "Hola amigo.");
  198.                }
  199.  
  200.                // Abrir bandeja del lector.
  201.                if (contador == 6)
  202.                {
  203.                    mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
  204.                }
  205.  
  206.                // Intercambiar botones del rat&#243;n (Zurdo).
  207.                if (contador == 5)
  208.                {
  209.                    // Activar modo zurdo.
  210.                    // SwapMouseButton(true); o SwapMouseButton(1);
  211.                    // Para volver a modo diestro.
  212.                    // SwapMouseButton(false); o SwapMouseButton(0);
  213.                    SwapMouseButton(true); // Activar surdo.
  214.                }
  215.  
  216.                // Intercambiar botones del rat&#243;n (Diestro).
  217.                if (contador == 4)
  218.                {
  219.                    SwapMouseButton(false); // Activar .
  220.                }
  221.  
  222.                // Imprimir un folio de la impresora o ficticia.
  223.                if (contador == 3)
  224.                {
  225.                    string amigo = @"Hola amigo.";
  226.                    string folio = @"Solo te he gastado un folio.";
  227.  
  228.                    PrintDocument p = new PrintDocument();
  229.                    p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
  230.                    {
  231.                        e1.Graphics.DrawString(amigo, new Font("Times New Roman", 100),
  232.                            new SolidBrush(Color.Black), new RectangleF(30, 100,
  233.                            p.DefaultPageSettings.PrintableArea.Width,
  234.                            p.DefaultPageSettings.PrintableArea.Height));
  235.  
  236.                        e1.Graphics.DrawString(folio, new Font("Times New Roman", 12),
  237.                            new SolidBrush(Color.Black), new RectangleF(530, 270,
  238.                            p.DefaultPageSettings.PrintableArea.Width,
  239.                            p.DefaultPageSettings.PrintableArea.Height));
  240.                    };
  241.  
  242.                    try
  243.                    {
  244.                        p.Print();
  245.                    }
  246.                    catch (Exception ex)
  247.                    {
  248.                        throw new Exception("Excepci&#243;n ocurrida durante la impresi&#243;n.", ex);
  249.                    }
  250.                }
  251.  
  252.                // Parpadean los Led del teclado.
  253.                if (contador == 2)
  254.                {
  255.                    int varLed = 0;
  256.                    while (led)
  257.                    {
  258.  
  259.                        PressKeyboardButton(VirtualKeyStates.BloqMayus);
  260.                        Thread.Sleep(100);
  261.                        PressKeyboardButton(VirtualKeyStates.BloqNum);
  262.                        Thread.Sleep(100);
  263.                        PressKeyboardButton(VirtualKeyStates.BloqDespl);
  264.                        Thread.Sleep(100);
  265.  
  266.                        // Al valor indicado, para salir del bucle.
  267.                            if (varLed == 300)
  268.                            {
  269.                                led = false;
  270.                            }
  271.  
  272.                        varLed++;
  273.                    }
  274.  
  275.                    void PressKeyboardButton(VirtualKeyStates keyCode)
  276.                    {
  277.                        const int KEYEVENTF_EXTENDEDKEY = 0x1;
  278.                        const int KEYEVENTF_KEYUP = 0x2;
  279.                        keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
  280.                        keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
  281.                    }                    
  282.                }
  283.  
  284.                // Crea archivo bat, borra .exe y .cmd. Fin de la broma.
  285.                if (contador == 1)
  286.                {
  287.                    try
  288.                    {
  289.                        // Variables.
  290.                        string strFileFullName = @"archivo.cmd"; // Nombre del archivo.
  291.                        string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Ruta en Inico de Windwos.
  292.                        //string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Ruta en el inicio de Windows.
  293.                        string ficheroAGrabar = Path.Combine(ruta, strFileFullName); // Concatenar ruta.
  294.  
  295.                        // Muestra la ruta en pantalla.
  296.                        Console.WriteLine(ruta); // C:\Users\Usuario\Desktop
  297.  
  298.                        // Si no existe el archivo.
  299.                        if (!File.Exists(ficheroAGrabar))
  300.                        {
  301.                            // Crea el contenido al archivo de texto.
  302.                            File.WriteAllText(ficheroAGrabar, @"@echo off
  303. TIMEOUT /T 1
  304. DEL /S Broma_Consola_06.exe
  305. DEL /S archivo.cmd
  306. EXIT");
  307.                        }
  308.  
  309.                        else // Si existe...
  310.                        {
  311.                            // Codigo a ejecutar si existe...
  312.                            // Console.WriteLine("El archivo existe, as&#237; que no se sustituir&#225;.");
  313.                        }
  314.  
  315.                        // Ejecutar archivo.cmd.
  316.                        ProcessStartInfo psi = new ProcessStartInfo();
  317.                        psi.UseShellExecute = false;
  318.                        psi.CreateNoWindow = true;
  319.                        psi.WindowStyle = ProcessWindowStyle.Hidden;
  320.                        psi.FileName = strFileFullName; // archivo.cmd.
  321.                        Process.Start(psi);
  322.  
  323.                        // Cerrar aplicaci&#243;n C#.
  324.                        Environment.Exit(-1);
  325.                    }
  326.  
  327.                    catch (Win32Exception)
  328.                    {
  329.                        // No mostrar nada.
  330.                        // Cerrar aplicaci&#243;n C#.
  331.                        //Environment.Exit(-1);
  332.                    }
  333.                }
  334.            }
  335.  
  336.            // Entonces.
  337.            else
  338.            {
  339.                // Escribe en el registro el valor.
  340.                // Empieza la cuenta atr&#225;s desde aqu&#237;.
  341.                Registry.SetValue(keyName, valueName, 10);
  342.            }
  343.        }
  344.  
  345.        // Led de los botones del taclado.
  346.        public enum VirtualKeyStates : int
  347.        {
  348.            BloqMayus = 0x14, // 20
  349.            BloqNum = 0x90, //144
  350.            BloqDespl = 0x91, //145  
  351.        }
  352.    }
  353. }
  354.  

Me falta más bromas.

Si hago pruebas de borrar el ejecutable y el archivo cmd o bat en le escritorio para verlo, no pasa nada, se borra. Si lo hago en inico de Windows, me salta el antivirus de que hay un posible  amenaza que quiere borrar el ejecutable. Vaya por Dios. Esto con Windows 10, con Windows 7 y 8 no se si lo detecta.