Friday, October 29, 2010

C# Tutorial: Simple Password Generator [Add Text to Clipboard]

Here is the code

using System.IO;

Random rnd = new Random(); int[] symb = { 33, 35, 36, 37, 38, 42, 95 }; int length; 
private void button2_Click(object sender, EventArgs e)
{
    StringWriter sw = new StringWriter(); length = Convert.ToInt32(textBox1.Text);
    for (; length > 0; length--)
    {
        switch (rnd.Next(1, 5))
        {
            case 1: sw.Write((char)rnd.Next(65, 91)); break;
            case 2: sw.Write((char)rnd.Next(97, 123)); break;
            case 3: sw.Write((char)rnd.Next(48, 58)); break;
            case 4: sw.Write((char)symb[rnd.Next(0, 7)]); break;  
        }
    }
    textBox2.Text = sw.ToString(); 
}

private void button1_Click(object sender, EventArgs e)
{
    Clipboard.SetText(textBox2.Text);   
}

Or download the solution

Wednesday, October 27, 2010

Ultimate Keylogger - Global KeyBoard Hook [C# Tutorial]

!!! --> First download my GlobalKeyboardHook <-- !!!

Here's how to use it

GlobalKeyboardHook gHook; 
private void Form1_Load(object sender, EventArgs e)
{
   gHook = new GlobalKeyboardHook(); // Create a new GlobalKeyboardHook
   // Declare a KeyDown Event
   gHook.KeyDown += new KeyEventHandler(gHook_KeyDown);
   // Add the keys you want to hook to the HookedKeys list
   foreach (Keys key in Enum.GetValues(typeof(Keys)))
       gHook.HookedKeys.Add(key);
}

// Handle the KeyDown Event
public void gHook_KeyDown(object sender, KeyEventArgs e)
{
   textBox1.Text += ((char)e.KeyValue).ToString();
}

private void button1_Click(object sender, EventArgs e)
{
   gHook.hook();
}

private void button2_Click(object sender, EventArgs e)
{
   gHook.unhook();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   gHook.unhook();
}
Using this keylogger to log/record other people's keystrokes without their knowledge can be considered as an illegal activity! It is the final user's responsibility to obey all applicable local,state,and federal laws! This tutorial is intended for educational purpose only! I assume NO liability and I'm NOT responsible for any misuse or damage caused by this keylogger!

Saturday, October 23, 2010

XNA Tutorial: How to Add a Song, Background and Video

Here is the code

Texture2D background; Video video; VideoPlayer player = new VideoPlayer(); Song song; bool playerStarted = false;
Vector2 backPos = Vector2.Zero; Texture2D videoT;
// Load the content
song = Content.Load<Song>("Not As It Seems");
background = Content.Load<Texture2D>("Desert");
video = Content.Load<Video>("Wildlife");
player.Play(video);

// Play a song
if (player.State == MediaState.Stopped)
{
    if (MediaPlayer.State == MediaState.Stopped)
    {
        if (playerStarted)
            this.Exit();
        MediaPlayer.Play(song);
        playerStarted = true;
    }
}

// Draw the frames of the video and the othr sprites
if (player.State != MediaState.Stopped)
    videoT = player.GetTexture();
Rectangle screen = new Rectangle(GraphicsDevice.Viewport.X, GraphicsDevice.Viewport.Y,
    GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
if (videoT != null)
    spriteBatch.Draw(videoT, screen, Color.White);
if (player.State == MediaState.Stopped)
{
    spriteBatch.Draw(background, backPos, Color.White);
    spriteBatch.Draw(mytexture, sPos, Color.White);
    spriteBatch.Draw(ball, bPos, Color.White);
}
spriteBatch.End();

Or download the solution

Friday, October 22, 2010

Windows API Tutorial: Create a Simple Window [C++]

Here is the code

#include <Windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

// WinMain: The Application Entry Point
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR nCmdLine, int nCmdShow)
{
 // Register the window class
 const wchar_t CLASS_NAME[] = L"WindowClass";
 WNDCLASS wc = { };
 wc.lpfnWndProc = WindowProc;
 wc.lpszClassName = CLASS_NAME;
 wc.hInstance = hInstance;
 RegisterClass(&wc);
 // Create the window
 HWND hwnd = CreateWindowEx(
  0,
  CLASS_NAME,
  L"MyFirstWindow",
  WS_OVERLAPPEDWINDOW,
  CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,
  NULL,NULL,hInstance,NULL);

 if(hwnd == 0)
  return 0;
 // Show the window
 ShowWindow(hwnd,nCmdShow);
 nCmdShow = 1;
 // The Message loop
 MSG msg = { }; 
 while(GetMessage(&msg,NULL,0,0))
 {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
 }
 return 0;
}
// Window Procedure function
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
 switch(uMsg)
 {
 case WM_DESTROY:PostQuitMessage(0); return 0;
 case WM_PAINT:
  {
   PAINTSTRUCT ps;
   HDC hdc = BeginPaint(hwnd,&ps);
   FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+5));
   EndPaint(hwnd,&ps);
  }return 0;
 case WM_CLOSE:
  {
   if(MessageBox(hwnd,L"Do you want to exit?",L"EXIT",MB_OKCANCEL)==IDOK)
    DestroyWindow(hwnd);
  }return 0;
 }
 return DefWindowProc(hwnd,uMsg,wParam,lParam); // Default Message Handling
}

Or download the solution(C++)

Wednesday, October 20, 2010

C# Tutorial: Simple Task Manager [Kill a Process]

Here is the code

using System.Diagnostics; 
//////////////////////////////////////////////
Process[] procs;
private void GetProcesses()
{
    procs = Process.GetProcesses();
    if (Convert.ToInt32(label2.Text) != procs.Length) // Check if new processes have been started or terminated
    {
        listBox1.Items.Clear(); 
        for (int i = 0; i < procs.Length; i++)
        {
            listBox1.Items.Add(procs[i].ProcessName);  // Add the process name to the listbox
        }
        label2.Text = procs.Length.ToString();  
    }
}
private void Form1_Load(object sender, EventArgs e)
{
    GetProcesses(); 
}

// Check every 1 second for changes in the processes list
private void timer1_Tick(object sender, EventArgs e)
{
    GetProcesses(); 
}

private void button1_Click(object sender, EventArgs e)
{
    procs[listBox1.SelectedIndex].Kill(); // Kill the process coresponding to the selected index of listbox1 
}

private void kIllProcessToolStripMenuItem_Click(object sender, EventArgs e)
{
    procs[listBox1.SelectedIndex].Kill();
}

Or download the solution

Monday, October 18, 2010

XNA Tutorial: Your first Game!

Here is the code

// Add these lines in the Game1() Method
// -------------------------------- //
// Set the window size
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
// You can also set it to fullscreen
// graphics.IsFullScreen = true;
// -------------------------------- //

// Above and in the LoadContent() Method
Texture2D mytexture; // A texture we can render (our sprite)
Vector2 sPos = Vector2.Zero; // Set the coordinates where the sprite will be drawn (2-dimensional space) 
// -------------------------------- //
mytexture = Content.Load("ball"); // Load the sprite
// -------------------------------- //

// Above and in the Update(GameTime gameTime) Method
Vector2 sSpeed = Vector2.One; // This is something like a direction indicator
// -------------------------------- //
if (Keyboard.GetState().IsKeyDown(Keys.Escape)) // Exit game when the ESC key is pressed
    this.Exit();
sPos += sSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds * 100; // Let's speed it up :)
int MaxX = graphics.GraphicsDevice.Viewport.Width - mytexture.Width;
int MinX = 0;
int MaxY = graphics.GraphicsDevice.Viewport.Height - mytexture.Height;
int MinY = 0;
// Check if the sprite hits the sides of the window. If it does so then make it to move the opposite direction.
if (sPos.X > MaxX)
{
    sSpeed.X *= -1;
    sPos.X = MaxX;
}
else if (sPos.X < MinX) 
{
    sSpeed.X *= -1;
    sPos.X = MinX; 
}
if (sPos.Y > MaxY)
{
    sSpeed.Y *= -1;
    sPos.Y = MaxY;
}
else if (sPos.Y < MinY) 
{
    sSpeed.Y *= -1;
    sPos.Y = MinY;
}
// -------------------------------- //

// Add these lines in the Draw(GameTime gameTime) Method
// -------------------------------- //
GraphicsDevice.Clear(Color.Red); // You can change the background color here
// Draw the sprite
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
spriteBatch.Draw(mytexture, sPos, Color.White);
spriteBatch.End(); 
// -------------------------------- //

Or download the solution

Sunday, October 17, 2010

C# Tutorial: Read/Write Characters from/to a String [Simple TextEncoder]

Here is the code

private void button3_Click(object sender, EventArgs e)
{
    StringReader str = new StringReader(textBox1.Text); // Read from textBox1.Text.
    StringWriter stw = new StringWriter();
    // This algorithm reverses the code (ASCII) of a char. Example: "a" is 97; the new code will be 79, wich is "O".
    int key, chr, newChr;
    do
    {
        key = str.Read(); // Read the int value (ASCII code) of the char
        chr = key; newChr = 0;
        // Reverse the code of the char
        while (key != -1 && chr != 0)
        {
            newChr = newChr * 10 + chr % 10;
            chr /= 10;
        }
        // Add the new char to the StringWriter
        if (key != -1) stw.Write((char)newChr);
        // Repeat this while there are chars in the string. -1 means the end of a string.
    } while (key != -1);
    // Converts stw to string and adds it to textBox1.Text.
    textBox1.Text = stw.ToString(); 
}

Or download the solution

Saturday, October 16, 2010

C# Tutorial: NotifyIcon with ContextMenuStrip [Tray Balloon]

Here is the code

private void Form1_SizeChanged(object sender, EventArgs e)
{
    // Check if the Form is minimized
    if (this.WindowState == FormWindowState.Minimized)
    {
        // If the notifyIcon1 doesn't have a Icon then it won't show up!
        notifyIcon1.Icon = SystemIcons.Application;
        notifyIcon1.BalloonTipText = "Your Form has minimized to tray";
        notifyIcon1.ShowBalloonTip(1000); 
    }
    // Check if the Form it's in Normal State
    else if (this.WindowState == FormWindowState.Normal)
    {
        notifyIcon1.BalloonTipText = "Your Form has come back to Normal";
        notifyIcon1.ShowBalloonTip(1000); 
    }
}

private void showFormToolStripMenuItem_Click(object sender, EventArgs e)
{
    this.WindowState = FormWindowState.Normal;
}

private void blablaToolStripMenuItem_Click(object sender, EventArgs e)
{
    MessageBox.Show("SUBSCRIBE :)");
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
    Application.Exit();
}

private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
    this.WindowState = FormWindowState.Normal;
}

Or download the solution

C# Tutorial: Read/Write File [Open/Save File]

Here is the code

using System.IO;
///////////////////////
private void button1_Click(object sender, EventArgs e)
{
    // Show the openFileDialog. When Ok is pressed, read the file and copy its content into the textBox1.
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        label1.Text = openFileDialog1.FileName;
        textBox1.Text = File.ReadAllText(label1.Text);  
    }
}

private void button2_Click(object sender, EventArgs e)
{
    // Show the saveFileDialog. When Ok is pressed, save the content of the textBox1 into the chosen file.
    if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        File.WriteAllText(saveFileDialog1.FileName, textBox1.Text);   
    }
}

Or download the solution

Friday, October 15, 2010

C# Tutorial: How to Disable Task Manager

Here is the code

/* 
    * NOTE: 
    * - You must have administrator privileges or this won't work !!!
    * - You must run VC# 2010 as Administrator or (again) this won't work !!!
    */
RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"); 
private void button1_Click(object sender, EventArgs e)
{
    key.SetValue("DisableTaskMgr", 1); 
}

private void button2_Click(object sender, EventArgs e)
{
    Registry.CurrentUser.DeleteSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
    // Or you can change the key value to 0
}

Or download the solution

Wednesday, October 13, 2010

C# Tutorial: Cross-Threading [Access a Form from a different Thread]

Here is the code

using System.Threading;
///////////////////////////////////////////
public Form1()
{
    InitializeComponent();
    // Create a new thread for Form2.
    Thread frm2 = new Thread(new ThreadStart(startForm2));
    frm2.Start(); 
}
Form2 form2 = new Form2(); 
public void startForm2()
{
    Application.Run(form2);   
}

public void transferText(string text)
{
    // Invoke the method of Form2's textBox1
    if (form2.textBox1.InvokeRequired)
        form2.textBox1.Invoke((MethodInvoker)delegate()
        {
            transferText(text);
        });
    else form2.textBox1.Text = text;
}

public void close()
{
    if (form2.textBox1.InvokeRequired)
        form2.textBox1.Invoke((MethodInvoker)delegate()
        {
            close();
        });
    else form2.Close();
}

private void button1_Click(object sender, EventArgs e)
{
    transferText(textBox1.Text);  
}

private void button2_Click(object sender, EventArgs e)
{
    close();
}

Or download the solution

Monday, October 11, 2010

How to fix the L4D2 scenefilecache.dll Trojan alarm [Kaspersky FIX]

Follow these steps and it should work (it worked for me):
1. Go to Kaspersky's Settings -> Click on Protection and uncheck Select action automatically -> Then, below Protection, click on File Anti-Virus and make sure Prompt for action is selected.
2. Exit Kaspersky (right click on the tray icon and click Exit)
3. Start Steam -> Go to Library -> Games -> Right click on Left 4 Dead 2 -> Properties -> Local Files -> Click on Verifi Integrity Of Game Chache -> Now wait (Steam will automatically download the missing files) -> Start L4D2 (to make sure it's working) then exit.
4. Start Kaspersky and wait to detect the file again. This time a window will appear prompting for an action. Choose SKIP !!!
5. Open Kaspersky's main window (double click on the tray icon). You should see Your computer is at risk / Threats have been detected. Click on that (DO NOT CLICK on Fix it now)
6. Protection state window will appear. In the Threats have been detected section click Details... button.
7. Then, below Status: Detected should be your trojan. Right click on it and choose Add to exclusions.
8. Now the Threats have been detected message should disappear. You can now play L4D2!


UPDATE FIX: If Kaspersky deletes your file again (your game will crash to desktop) then REDO Steps 2 and 3 !! (This motherfu**er doesn't give up)

Sunday, October 10, 2010

C# Tutorial: Create and Delete Registry Keys

Here is the code

Microsoft.Win32.RegistryKey key;
private void button1_Click(object sender, EventArgs e)
{
    // Create the registry key.
    // It is more secure to write data to the user folder — Microsoft.Win32.Registry.CurrentUser 
    // — rather than to the local computer — Microsoft.Win32.Registry.LocalMachine.
    key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("MyRegKey");
    key.SetValue("IsTutorial", "Yes");
    key.Close(); 
}

private void button2_Click(object sender, EventArgs e)
{
    // Delete a registry key
    Microsoft.Win32.Registry.CurrentUser.DeleteSubKey("MyRegKey"); 
}

private void Form1_Load(object sender, EventArgs e)
{
    // NOTE: Before typing this code make sure you have created the registry key
    // Otherwise you'll get an exception error !!! 
            
    // Open a registry key.
    // "true" means the key it's writable
            
    key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("MyRegKey",true);
    // An example of using the registry key
    if (key.GetValue("IsTutorial").ToString() == "Yes")
    {
        MessageBox.Show("This is a Tutorial!");
        key.SetValue("IsTutorial", "No");
    }
    else MessageBox.Show("This is Not a Tutorial!");
}

Or download the solution

Wednesday, October 6, 2010

C# Tutorial: Suppress a Key on a TextBox [Cancel KeyDown event]

Here is the code

using System.Media;
/////////////////////////////////
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if ((e.KeyValue < 48 || e.KeyValue > 57) && e.KeyCode != Keys.Delete && e.KeyCode != Keys.Back)
    {
        e.SuppressKeyPress = true;
        SystemSounds.Beep.Play();
    }
}

Ascii Table

Tuesday, October 5, 2010

How to Enable Line Numbers in Visual C++/C# 2010

Open Visual C++ 2010

Go to Tools

And from the Tools menu

Choose Options










A new window will appear

Go to Text Editor








And Choose C/C++

Then check Line Numbers

Hit OK






Do the same for Visual C# 2010
but make sure you check Show all settings


Friday, October 1, 2010

C# Tutorial: Create a Glossy Button [Custom Controls]

Here is the code

// Import the Gdi32 DLL
[DllImport("Gdi32.dll",EntryPoint="CreateRoundRectRgn")]
// Import the Method from DLL. With this method you can create a Form with rounded corners
private static extern IntPtr CreateRoundRectRgn(int leftRect,int topRect, int rightRect, int bottomRect, int wEllipse, int hEllipse);
// Create a Pen that will draw the border of the button.
Pen p = new Pen(Color.Aqua);
// Configure the BtnText Property
[Description("The text associated with the control")]
[Category("Appearance")]
public string BtnText
{
    get
    {
        return label1.Text; 
    }
    set
    {
        label1.Text = value;
        label1.Location = new Point(this.Width / 2 - label1.Width / 2, this.Height / 2 - label1.Height / 2);  
    }
}
// Set the font of label1 through the Font Property of GlossyButton
public override Font Font
{
    get
    {
        return label1.Font;
    }
    set
    {
        label1.Font = value;
        // Center the label
        label1.Location = new Point(this.Width / 2 - label1.Width / 2, this.Height / 2 - label1.Height / 2);
    }
}

protected void onMouseEnter()
{
    p.Color = Color.Red; this.BackColor = Color.Firebrick; this.Invalidate(); 
}

protected void onMouseDown()
{
    this.BackColor = Color.Maroon; this.Invalidate();  
}

protected void NormalStyle()
{
    p.Color = Color.Aqua; this.BackColor = Color.DodgerBlue; this.Invalidate(); 
}

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    // Create the rounded corners for your form (in this case your button)
    this.Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, this.Width + 1, this.Height + 1, 3, 3));
    // Create a transparent white gradient
    LinearGradientBrush lb = new LinearGradientBrush(new Rectangle(0, 0, this.Width, this.Height), Color.FromArgb(150, Color.White), 

Color.FromArgb(50, Color.White), LinearGradientMode.Vertical);
    // Draw the gradient
    e.Graphics.FillRectangle(lb, 2, 2, this.Width - 6, this.Height / 2);
    // Draw the border
    e.Graphics.DrawRectangle(p, 0, 0, this.Width - 3, this.Height - 3);   
}
protected override void OnSizeChanged(EventArgs e)
{
    base.OnSizeChanged(e);
    // Center the label
    label1.Location = new Point(this.Width / 2 - label1.Width / 2, this.Height / 2 - label1.Height / 2);
}

protected override void OnMouseEnter(EventArgs e)
{
    base.OnMouseEnter(e); onMouseEnter();
}
protected override void OnMouseLeave(EventArgs e)
{
    base.OnMouseLeave(e); NormalStyle();
}
protected override void OnMouseDown(MouseEventArgs e)
{
    base.OnMouseDown(e); onMouseDown();
}
protected override void OnMouseUp(MouseEventArgs e)
{
    base.OnMouseUp(e); onMouseEnter();
}

private void label1_MouseEnter(object sender, EventArgs e)
{
    onMouseEnter();
}

private void label1_MouseLeave(object sender, EventArgs e)
{
    NormalStyle();
}

private void label1_MouseDown(object sender, MouseEventArgs e)
{
    onMouseDown();
}

private void label1_MouseUp(object sender, MouseEventArgs e)
{
    onMouseEnter();
}

Or download the solution