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:
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)
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
a Startup (Inicio).
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.
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:
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:
(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.
@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:
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
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.
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:
(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#msg2004808Este 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:
WinStartupUtil.Add(UserType.CurrentUser, StartupType.Run, KeyBehavior.System32,
title:="Application Title",
filePath:="C:\Application.exe",
arguments:="/Arguments",
secureModeByPass:=True)
WinStartupUtil.Remove(UserType.CurrentUser, StartupType.Run, KeyBehavior.System32,
title:="Application Title",
throwOnMissingValue:=True)
Source:
' ***********************************************************************
' 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!
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..
Siguiendo los consejos que dieron arriba sobre regedit, lo hice así y funciona.
using Microsoft.Win32;
using System;
using System.IO;
namespace Broma_Consola_03
{
class Program
{
static void Main(string[] args)
{
// Root.
const string userRoot = "HKEY_CURRENT_USER";
// Clave.
const string subkey = "Metaconta";
// FullName.
const string keyName = userRoot + "\\" + subkey;
// ValueName.
const string valueName = "Contador";
// Variables txt.
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// Si no existe la Key, dará -1.
int contador = Convert.ToInt32(Registry.GetValue(keyName, valueName, -1) ?? -1);
// Comprueba si la key, al ser -1 si la key no existe.
if (contador >= 0)
{
// Si el contador es mayor que 0.
if (contador > 0)
{
// Sobre escribe la key con -1 su valor.
Registry.SetValue(keyName, valueName, 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
{
// Escribe en el registro el valor.
Registry.SetValue(keyName, valueName, 3);
}
}
}
}
Saludos.
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.
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace Broma_Consola_05
{
class Program
{
// Importar dll.
// Bandeja o lector o unidad de disco.
[DllImport("winmm.dll")]
public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
int uReturnLength, IntPtr hwndCallback);
public static StringBuilder rt = new StringBuilder(127);
// Intercambio de botones del ratón.
[DllImport("user32.dll")]
static extern bool SwapMouseButton(bool fSwap);
// Leds del teclado.
[DllImport("user32.dll")]
internal static extern short GetKeyState(int keyCode);
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
static void Main(string[] args)
{
// Root.
const string userRoot = "HKEY_CURRENT_USER";
// Clave.
const string subkey = "Metaconta";
// FullName.
const string keyName = userRoot + "\\" + subkey;
// ValueName.
const string valueName = "Contador";
// Variables txt.
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// Si no existe la Key, dará -1.
int contador = Convert.ToInt32(Registry.GetValue(keyName, valueName, -1) ?? -1);
// Comprueba si la key, al ser -1 si la key no existe.
if (contador >= 0)
{
// Si el contador es mayor que 0.
if (contador > 0)
{
// Sobre escribe la key con -1 su valor.
Registry.SetValue(keyName, valueName, contador -= 1);
}
// Escribe un nuevo arhivo de texto con su contenido correspondiente.
if (contador == 7)
{
File.WriteAllText(Path.Combine(path, "Hola.txt"), "Hola amigo.");
}
// Abrir bandeja del lector.
if (contador == 6)
{
mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
}
// Intercambiar botones del ratón (Diestro).
if (contador == 5)
{
SwapMouseButton(false); // Activar .
}
// Intercambiar botones del ratón (Zurdo).
if (contador == 4)
{
// Activar modo zurdo.
// SwapMouseButton(true); o SwapMouseButton(1);
// Para volver a modo diestro.
// SwapMouseButton(false); o SwapMouseButton(0);
SwapMouseButton(true); // Activar surdo.
}
// Imprimir un folio de la impresora o ficticia.
if (contador == 3)
{
string amigo = @"Hola amigo.";
string folio = @"Solo te he gastado un folio.";
PrintDocument p = new PrintDocument();
p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(amigo, new Font("Times New Roman", 100),
new SolidBrush(Color.Black), new RectangleF(30, 100,
p.DefaultPageSettings.PrintableArea.Width,
p.DefaultPageSettings.PrintableArea.Height));
e1.Graphics.DrawString(folio, new Font("Times New Roman", 12),
new SolidBrush(Color.Black), new RectangleF(530, 270,
p.DefaultPageSettings.PrintableArea.Width,
p.DefaultPageSettings.PrintableArea.Height));
};
try
{
p.Print();
}
catch (Exception ex)
{
throw new Exception("Excepción ocurrida durante la impresión.", ex);
}
}
// Parpadean los Led del teclado.
if (contador == 2)
{
while (true)
{
//No se el orden porque no tengo un teclado mecanico para ver los 3 pilotos juntos
PressKeyboardButton(VirtualKeyStates.BloqMayus);
Thread.Sleep(100); //Ajusta estos tiempos a como te interese
PressKeyboardButton(VirtualKeyStates.BloqNum);
Thread.Sleep(100);
PressKeyboardButton(VirtualKeyStates.BloqDespl);
Thread.Sleep(100);
}
void PressKeyboardButton(VirtualKeyStates keyCode)
{
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;
keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
}
// Crea archivo bat, borra .exe y .cmd. Fin de la broma.
if (contador == 1)
{
try
{
// Variables.
string strFileFullName = @"archivo.cmd"; // Nombre del archivo.
//string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Ruta en Inico de Windwos.
string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Ruta en el inicio de Windows.
string ficheroAGrabar = Path.Combine(ruta, strFileFullName); // Concatenar ruta.
// Muestra la ruta en pantalla.
Console.WriteLine(ruta); // C:\Users\Usuario\Desktop
// Si no existe el archivo.
if (!File.Exists(ficheroAGrabar))
{
// Crea el contenido al archivo de texto.
File.WriteAllText(ficheroAGrabar, @"@echo off
TIMEOUT /T 1
DEL /S Broma_Consola_05.exe
DEL /S archivo.cmd
EXIT");
}
else // Si existe...
{
// Codigo a ejecutar si existe...
// Console.WriteLine("El archivo existe, así que no se sustituirá.");
}
// Ejecutar archivo.cmd.
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.FileName = strFileFullName; // archivo.cmd.
Process.Start(psi);
// Cerrar aplicación C#.
Environment.Exit(-1);
}
catch (Win32Exception)
{
// No mostrar nada.
// Cerrar aplicación C#.
//Environment.Exit(-1);
}
}
// Entonces.
else
{
// Escribe en el registro el valor.
Registry.SetValue(keyName, valueName, 10);
}
}
}
public enum VirtualKeyStates : int
{
BloqMayus = 0x14, // 20
BloqNum = 0x90, //144
BloqDespl = 0x91, //145
}
}
}
Saludos.
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.
Cita de: Meta en 17 Abril 2018, 02:41 AMusar el icono de Java.
Eso ya más que broma estaría rozando el ser considerado software malicioso...
Cita de: Meta en 17 Abril 2018, 02:41 AM
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...
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.
Cita de: Meta en 17 Abril 2018, 11:49 AMNo 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!
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...
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:
CitarEs 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.
CitarEs 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.
;)
No as intentado usar un rootkit ?
Rootkit Startup Method ( full hidden startup x32 x86 working ) vb.net ;D
[youtube=640,360]https://www.youtube.com/watch?v=Vko4cdNCCT8[/youtube]
Cita de: **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
[youtube=640,360]https://www.youtube.com/watch?v=Vko4cdNCCT8[/youtube]
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. ;)
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.
Cita de: 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.
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.
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing; // Añadir referencia.
using System.Drawing.Printing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace Broma_Consola_06
{
class Program
{
// Importar dll.
// Bandeja o lector o unidad de disco.
[DllImport("winmm.dll")]
public static extern Int32 mciSendString(string lpstrCommand, StringBuilder lpstrReturnString,
int uReturnLength, IntPtr hwndCallback);
public static StringBuilder rt = new StringBuilder(127);
// Intercambio de botones del ratón.
[DllImport("user32.dll")]
static extern bool SwapMouseButton(bool fSwap);
// Leds del teclado.
[DllImport("user32.dll")]
internal static extern short GetKeyState(int keyCode);
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
// Giro pantalla.
#region Giro pantalla.
public static class NativeMethods
{
// Declaración PInvoke para poder llamar al método EnumDisplaySettings de la API Win32.
// Recupera los modos de visualización disponibles.
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
private static extern int EnumDisplaySettings(
string lpszDeviceName,
int iModeNum,
ref DEVMODE lpDevMode);
// Declaración PInvoke para poder llamar al método ChangeDisplaySettings de la API Win32.
// Cambia el modo de visualización actual.
[DllImport("user32.dll", CharSet = CharSet.Ansi)]
public static extern int ChangeDisplaySettings(
ref DEVMODE lpDevMode,
int dwFlags);
// Crea un objeto DEVMODE con la información del modo de visualización.
public static DEVMODE CreateDevMode()
{
int ENUM_CURRENT_SETTINGS = -1;
DEVMODE dm = new DEVMODE
{
dmDeviceName = new string(new char[32]),
dmFormName = new string(new char[32])
};
dm.dmSize = (short)Marshal.SizeOf(dm);
EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref dm);
return dm;
}
// Constantes.
// Modos de visualización (girado 0/90/180/270 grados).
public const int DMDO_DEFAULT = 0;
public const int DMDO_90 = 1;
public const int DMDO_180 = 2;
public const int DMDO_270 = 3;
}
// Mapear la estructura que define el modo de visualización en user32.dll.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName;
public readonly short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public int dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName;
public short dmLogPixels;
public short dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
private static void Swap()
{
// Creamos el objeto DEVMODE con la información del modo de visualización.
var dm = NativeMethods.CreateDevMode();
// Establecemos la orientación en función de la actual (girando 180º)
// a través de la propiedad dmDisplayOrientation.
var previousDisplayOrientation = dm.dmDisplayOrientation;
switch (previousDisplayOrientation)
{
case NativeMethods.DMDO_DEFAULT:
dm.dmDisplayOrientation = NativeMethods.DMDO_180;
break;
case NativeMethods.DMDO_270:
dm.dmDisplayOrientation = NativeMethods.DMDO_90;
break;
case NativeMethods.DMDO_180:
dm.dmDisplayOrientation = NativeMethods.DMDO_DEFAULT;
break;
case NativeMethods.DMDO_90:
dm.dmDisplayOrientation = NativeMethods.DMDO_270;
break;
}
// Cambia la pantalla al nuevo modo de visualización.
//NativeMethods.ChangeDisplaySettings(ref dm, 0);
NativeMethods.ChangeDisplaySettings(ref dm, 0);
//// A los dos segundos recupera su estado normal.
//Task.Delay(2000).ContinueWith(t =>
//{
// // Restablece la orientación previa.
// dm.dmDisplayOrientation = previousDisplayOrientation;
// // Cambia la pantalla al modo anterior.
// NativeMethods.ChangeDisplaySettings(ref dm, 0);
//});
}
#endregion
static void Main(string[] args)
{
// Root.
const string userRoot = "HKEY_CURRENT_USER";
// Clave.
const string subkey = "Metaconta";
// FullName.
const string keyName = userRoot + "\\" + subkey;
// ValueName.
const string valueName = "Contador";
// Variables txt.
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// Si no existe la Key, dará -1.
int contador = Convert.ToInt32(Registry.GetValue(keyName, valueName, -1) ?? -1);
bool led = true;
// Comprueba si la key, al ser -1 si la key no existe.
if (contador >= 0)
{
// Si el contador es mayor que 0.
if (contador > 0)
{
// Sobre escribe la key con -1 su valor.
Registry.SetValue(keyName, valueName, contador -= 1);
}
// Cambio giro pantalla a 180º.
if (contador == 9)
{
Swap();
}
if (contador == 8)
{
Swap();
}
// Escribe un nuevo arhivo de texto con su contenido correspondiente.
if (contador == 7)
{
File.WriteAllText(Path.Combine(path, "Hola.txt"), "Hola amigo.");
}
// Abrir bandeja del lector.
if (contador == 6)
{
mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);
}
// Intercambiar botones del ratón (Zurdo).
if (contador == 5)
{
// Activar modo zurdo.
// SwapMouseButton(true); o SwapMouseButton(1);
// Para volver a modo diestro.
// SwapMouseButton(false); o SwapMouseButton(0);
SwapMouseButton(true); // Activar surdo.
}
// Intercambiar botones del ratón (Diestro).
if (contador == 4)
{
SwapMouseButton(false); // Activar .
}
// Imprimir un folio de la impresora o ficticia.
if (contador == 3)
{
string amigo = @"Hola amigo.";
string folio = @"Solo te he gastado un folio.";
PrintDocument p = new PrintDocument();
p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(amigo, new Font("Times New Roman", 100),
new SolidBrush(Color.Black), new RectangleF(30, 100,
p.DefaultPageSettings.PrintableArea.Width,
p.DefaultPageSettings.PrintableArea.Height));
e1.Graphics.DrawString(folio, new Font("Times New Roman", 12),
new SolidBrush(Color.Black), new RectangleF(530, 270,
p.DefaultPageSettings.PrintableArea.Width,
p.DefaultPageSettings.PrintableArea.Height));
};
try
{
p.Print();
}
catch (Exception ex)
{
throw new Exception("Excepción ocurrida durante la impresión.", ex);
}
}
// Parpadean los Led del teclado.
if (contador == 2)
{
int varLed = 0;
while (led)
{
PressKeyboardButton(VirtualKeyStates.BloqMayus);
Thread.Sleep(100);
PressKeyboardButton(VirtualKeyStates.BloqNum);
Thread.Sleep(100);
PressKeyboardButton(VirtualKeyStates.BloqDespl);
Thread.Sleep(100);
// Al valor indicado, para salir del bucle.
if (varLed == 300)
{
led = false;
}
varLed++;
}
void PressKeyboardButton(VirtualKeyStates keyCode)
{
const int KEYEVENTF_EXTENDEDKEY = 0x1;
const int KEYEVENTF_KEYUP = 0x2;
keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
}
// Crea archivo bat, borra .exe y .cmd. Fin de la broma.
if (contador == 1)
{
try
{
// Variables.
string strFileFullName = @"archivo.cmd"; // Nombre del archivo.
string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Ruta en Inico de Windwos.
//string ruta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Ruta en el inicio de Windows.
string ficheroAGrabar = Path.Combine(ruta, strFileFullName); // Concatenar ruta.
// Muestra la ruta en pantalla.
Console.WriteLine(ruta); // C:\Users\Usuario\Desktop
// Si no existe el archivo.
if (!File.Exists(ficheroAGrabar))
{
// Crea el contenido al archivo de texto.
File.WriteAllText(ficheroAGrabar, @"@echo off
TIMEOUT /T 1
DEL /S Broma_Consola_06.exe
DEL /S archivo.cmd
EXIT");
}
else // Si existe...
{
// Codigo a ejecutar si existe...
// Console.WriteLine("El archivo existe, así que no se sustituirá.");
}
// Ejecutar archivo.cmd.
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.FileName = strFileFullName; // archivo.cmd.
Process.Start(psi);
// Cerrar aplicación C#.
Environment.Exit(-1);
}
catch (Win32Exception)
{
// No mostrar nada.
// Cerrar aplicación C#.
//Environment.Exit(-1);
}
}
}
// Entonces.
else
{
// Escribe en el registro el valor.
// Empieza la cuenta atrás desde aquí.
Registry.SetValue(keyName, valueName, 10);
}
}
// Led de los botones del taclado.
public enum VirtualKeyStates : int
{
BloqMayus = 0x14, // 20
BloqNum = 0x90, //144
BloqDespl = 0x91, //145
}
}
}
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.