PDA

View Full Version : C++ Just messing around.



Brandon
11-30-2011, 03:30 AM
This is my first WINAPI application.. I usually write consoles or forms..

12133

Description:
Restarts Simba/Smart Depending on the text in the debug box.. If it finds the strings: "Successfully Executed" OR "Runescape has been updated", It will restart the last script that was running when those strings occured.. Closes Simba/Smart Naturally (Not by force). Uses OpenFileDialog() to let the user choose a file. If smart applet declaration error is found, it will automatically run RS in a new browser window, wait for it to load.. and then exit the window and restart everything for you.


Possible Problems:
One string that I'm not sure I got right is: "Runescape has been updated".. Not sure if that's the exact text that simba displays in the debug box.

Future Updates (if anyone uses this):

Detect simba locations.
{DriveHere} :/Simba/{0 - any amount of folders here}/Simba.exe

Future Plans (if anyone uses this):
Better handling of sleep methods for the threads.


Main.cpp


#include <windows.h>
#include <iostream>
#include <vector>
#include <TCHAR.h>
#include <algorithm>
#include <sstream>
#include <conio.h>
#define MAIN_ICON 2
#include <fstream>

using namespace std;

struct FindWindowData
{
FindWindowData(TCHAR const * windowTitle) : WindowTitle(windowTitle), ResultHandle(0)
{
}

basic_string<TCHAR> WindowTitle;
HWND ResultHandle;
};

void Open(const char *url)
{
string browser_app;

//Find the default application.
HKEY key;
DWORD dwValue;
char *str;
std::string lookup;

if (RegOpenKeyEx(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\Shell\\Associations\ \UrlAssociations\\http\\UserChoice", 0, KEY_READ, &key) == ERROR_SUCCESS)
{
if (RegQueryValueEx(key, "Progid", NULL, NULL, NULL, &dwValue) == ERROR_SUCCESS)
{
str = new char[dwValue + 1];

RegQueryValueEx(key, "Progid", NULL, NULL, (BYTE*)str, &dwValue);
RegCloseKey(key);

std::stringstream buffer;
buffer << str << "\\shell\\open\\command";
lookup = buffer.str();

delete [] str;
}
}

if (RegOpenKeyEx(HKEY_CLASSES_ROOT, lookup.length() > 0 ? lookup.c_str() : "HTTP\\shell\\open\\command", 0, KEY_READ, &key) == ERROR_SUCCESS)
{
if (!RegQueryValueEx(key, NULL, NULL, NULL, NULL, &dwValue) == ERROR_SUCCESS) return;

str = new char[dwValue + 1];

RegQueryValueEx(key, NULL, NULL, NULL, (BYTE*)str, &dwValue);
RegCloseKey(key);

browser_app = str;
delete[] str;

//Remove all stuff from the path and leave only the executable and the path

if (browser_app.at(0) == '"')
{
browser_app.erase(0, 1);

if (browser_app.find('"') > 0)
browser_app.resize(browser_app.find('"'));
}
else
{
if (browser_app.find(' ') > 0)
browser_app.resize(browser_app.find(' '));
}
}

string u = url;

unsigned short found = browser_app.find("\\");
while (found != string::npos)
{
browser_app.replace(found, 1, "/");
found = browser_app.find("\\");
}

u = " -new-window " + u;
cout<<browser_app;

//browser_app = "\"" + browser_app + "\"" + " -new-window " + u;
//system(browser_app.c_str());

ShellExecute(NULL, NULL, browser_app.c_str(), u.c_str(), NULL, SW_SHOW);
}

string Mid(string& str, int pos1, int pos2)
{
int i;
string temp = "";
for(i = pos1; i < pos2; i++)
{
temp += str[i];
}

return temp;
}

string capital(string name)
{

for (unsigned short i = 0; i < name.length(); i++)
{
name[i] = toupper(name[i]);
}

return name;

}

string Left(string& str, int pos)
{
int i;
string temp = "";
for(i = 0; i < pos; i++)
{
temp += str[i];
}

return temp;
}

BOOL CALLBACK FindWindowImpl(HWND hWnd, LPARAM lParam)
{
FindWindowData * p = reinterpret_cast<FindWindowData*>(LongToPtr(lParam));
if(!p)
{
// Finish enumerating we received an invalid parameter..
return FALSE;
}

int length = GetWindowTextLength(hWnd) + 1;
if(length > 0)
{
vector<TCHAR> buffer(size_t( length), 0);
if(GetWindowText(hWnd, &buffer[0], length))
{
if(_strnicmp(&buffer[0], p->WindowTitle.c_str(), min(buffer.size(), p->WindowTitle.size())) == 0)
{
p->ResultHandle = hWnd;
// Finish enumerating we found what we need..
return FALSE;
}
}
}
// Continue enumerating
return TRUE;
}

// Returns the window handle when found if it returns 0 GetLastError() will return more information..
HWND FindWindowStart(TCHAR const * windowTitle)
{

if(!windowTitle)
{
SetLastError(ERROR_INVALID_PARAMETER);
return 0;
}

FindWindowData data(windowTitle);
if( !EnumWindows(FindWindowImpl, PtrToLong(&data)) && data.ResultHandle != 0)
{
SetLastError(ERROR_SUCCESS);
return data.ResultHandle;
}

// Return ERROR_FILE_NOT_FOUND in GetLastError
SetLastError(ERROR_FILE_NOT_FOUND);
return 0;
}

HWND Window;

BOOL CALLBACK WorkerProc(HWND hwnd, LPARAM lParam)
{
static TCHAR buffer[50];

GetWindowText(hwnd, buffer, 50);
if(_tcsstr(buffer, "Simba"))
{
Window = hwnd;
return FALSE;
}

return TRUE;
}

int SearchDirectory(vector<string> &refvecFiles, const string &refcstrRootDirectory, const string &refcstrExtension, bool bSearchSubdirectories = true)
{
string strFilePath; // Filepath
string strPattern; // Pattern
string strExtension; // Extension
HANDLE hFile; // Handle to file
WIN32_FIND_DATA FileInformation; // File information


strPattern = refcstrRootDirectory + "/*.*";

hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
if(hFile != INVALID_HANDLE_VALUE)
{
do
{
if(FileInformation.cFileName[0] != '.')
{
strFilePath.erase();
strFilePath = refcstrRootDirectory + "/" + FileInformation.cFileName;

if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(bSearchSubdirectories)
{
// Search subdirectory
int iRC = SearchDirectory(refvecFiles, strFilePath, refcstrExtension, bSearchSubdirectories);
if(iRC)
return iRC;
}
}
else
{
// Check extension
strExtension = FileInformation.cFileName;
strExtension = strExtension.substr(strExtension.rfind(".") + 1);

if(strExtension == refcstrExtension)
{
// Save filename
refvecFiles.push_back(strFilePath);
}
}
}
} while(::FindNextFile(hFile, &FileInformation) == TRUE);

// Close handle
::FindClose(hFile);

DWORD dwError = ::GetLastError();
if(dwError != ERROR_NO_MORE_FILES)
return dwError;
}

return 0;
}

string ScriptLoc;

int OpenFileDialog()
{
int iRC = 0;
vector<string> vecFiles;

// Search 'c:' for '.exe' files including subdirectories
iRC = SearchDirectory(vecFiles, "c:/Simba", "exe");
if(iRC)
{
cout << "Error " << iRC << endl;
return -1;
}

string SimbaCap = "Simba.exe";
string SimbaCom = "simba.exe";
string SimbaExe = "Simba.EXE";
string Simbaexe = "simba.exe";
string Buffer = "";

// Print results
for(vector<string>::iterator iter = vecFiles.begin(); iter != vecFiles.end(); ++iter)
{
Buffer = *iter + "\n";
if ((string::npos != Buffer.find(SimbaCap)) || (string::npos != Buffer.find(SimbaCom)) || (string::npos != Buffer.find(SimbaExe)) || (string::npos != Buffer.find(Simbaexe)))
{
Buffer = *iter;
break;
}
}

OPENFILENAME ofn;
char szFileName[MAX_PATH] = "";

ZeroMemory(&ofn, sizeof(ofn));

ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = "Simba Files (*.Simba)\0*.Simba\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY|OFN_ALLOWMULTISELECT;
ofn.lpstrDefExt = "Simba";

if(GetOpenFileName(&ofn))
{
string FileStr = szFileName;
ScriptLoc = Buffer + " -o " + FileStr + " -r";
}
else
{
MessageBox(NULL, "You have not selected a script. \nThe program will now terminate.", "No Script Selected", MB_ICONERROR);
exit(0);
}

return 0;
}

int children = 0;
vector<HWND>handles;

BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam)
{
children++;
handles.push_back(hwnd);
return TRUE;
}


static DWORD WINAPI Check(void *param)
{
system(ScriptLoc.c_str());
return 0;
}

HANDLE Running, Checking;

static DWORD WINAPI RunScript(void *param)
{
vector<HWND>chandles;

while(1)
{
Sleep(5000);
EnumWindows(WorkerProc, (LPARAM)NULL);

if(Window != NULL)
{
EnumChildWindows(Window, EnumChildProc, 0);
Sleep(150000);
for(unsigned short i = 0; i < handles.size(); i++)
{
EnumChildWindows(handles[i], EnumChildProc, 0);
if((FindWindowEx(handles[i], NULL, "Edit", NULL) != NULL) && (FindWindowEx(handles[i], NULL, "Window", NULL) == NULL))
{
HWND Debug = FindWindowEx(handles[i], NULL, "Edit", NULL);
if(Debug != NULL)
{
LRESULT length = SendMessage(Debug, WM_GETTEXTLENGTH, 0, 0);
char szText[length+1];
SendMessage(Debug, WM_GETTEXT, length+1, (LPARAM)szText);

string Updated = "RuneScape has been updated";
string Executed = "Successfully executed.";
string Buffer = szText;

HWND Smart = FindWindowStart("By BenLand100");
HWND SmartError = FindWindow("SunAwtDialog", "SMART");

if(SmartError != NULL)
{
cout<<"SMART Applet Declaration Error!"<<endl;
SendMessage(SmartError, WM_CLOSE, 0, (LPARAM)0);
Sleep(1000);
SendMessage(Window, WM_KEYDOWN, VK_F2, 0);
SendMessage(Window, WM_KEYUP, VK_F2, 0);
Sleep(2000);
SendMessage(Window, WM_KEYDOWN, VK_F2, 0);
SendMessage(Window, WM_KEYUP, VK_F2, 0);
Sleep(5000);
SendMessage(Window, WM_CLOSE, 0, (LPARAM)0);

if(Checking != NULL)
CloseHandle(Checking);

Open("--new-window http://www.runescape.com/game.ws?j=1");

int i = 0;
while(FindWindowStart("RuneScape - MMORPG - The No.1 Free Online Multiplayer Game") == NULL)
{
Sleep(1000); i++;
if((i >= 10) || (FindWindowStart("RuneScape - MMORPG - The No.1 Free Online Multiplayer Game") != NULL))
break;
}

HWND RSLoaded = FindWindowStart("RuneScape - MMORPG - The No.1 Free Online Multiplayer Game");
if(RSLoaded != NULL)
{
Sleep(120000); //Wait until webpage has loaded.. approx 2 mins to load RS I assume..
SendMessage(RSLoaded, WM_CLOSE, 0, (LPARAM)0);
Sleep(1000);
}

Checking = CreateThread(NULL, 0, Check, NULL, 0, 0);
Sleep(5000);
}

if ((string::npos != Buffer.find(Updated)) || (string::npos != Buffer.find(Executed)))
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HA NDLE), 12);
cout<<"\n\n\nRS Has been Updated, OR Successfully executed. Restarting The Client.\n\n\n";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HA NDLE), 8);

if(Smart != NULL)
{
SendMessage(Smart, WM_CLOSE, 0, (LPARAM)0);
Sleep(1000);
}

SendMessage(Window, WM_KEYDOWN, VK_F2, 0);
SendMessage(Window, WM_KEYUP, VK_F2, 0);
Sleep(2000);
SendMessage(Window, WM_KEYDOWN, VK_F2, 0);
SendMessage(Window, WM_KEYUP, VK_F2, 0);
Sleep(5000);
SendMessage(Window, WM_CLOSE, 0, (LPARAM)0);

if(Checking != NULL)
CloseHandle(Checking);

Checking = CreateThread(NULL, 0, Check, NULL, 0, 0);
Sleep(5000);
}
}
}
}
}
}
if(Running != NULL)
CloseHandle(Running);
return 0;
}


HINSTANCE g_hInst;

/* Declare Windows procedure */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/* Make the class name into a global variable */
char szClassName[] = "ScriptRestarter";

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
HWND hwnd; /* This is the handle for our window */
MSG messages; /* Here messages to the application are saved */
WNDCLASSEX wincl; /* Data structure for the windowclass */

/* The Window structure */
wincl.hInstance = hInstance;
wincl.lpszClassName = szClassName;
wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */
wincl.style = CS_DBLCLKS; /* Catch double-clicks */
wincl.cbSize = sizeof (WNDCLASSEX);

/* Use default icon and mouse-pointer */
wincl.hIcon = LoadIcon (NULL, MAKEINTRESOURCE(MAIN_ICON));
wincl.hIconSm = LoadIcon (NULL, MAKEINTRESOURCE(MAIN_ICON));
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL; /* No menu */
wincl.cbClsExtra = 0; /* No extra bytes after the window class */
wincl.cbWndExtra = 0; /* structure or the window instance */
/* Use Windows's default color as the background of the window */
wincl.hbrBackground = (HBRUSH) COLOR_WINDOW;

/* Register the window class, and if it fails quit the program */
if (!RegisterClassEx (&wincl))
return 0;

/* The class is registered, let's create the program*/
hwnd = CreateWindowEx (
WS_EX_TOOLWINDOW | WS_EX_APPWINDOW, /* Extended possibilites for variation */
szClassName, /* Classname */
"Script Loader v0.2", /* Title Text */
WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, /* default window */
CW_USEDEFAULT, /* Windows decides the position */
CW_USEDEFAULT, /* where the window ends up on the screen */
250, /* The programs width */
110, /* and height in pixels */
HWND_DESKTOP, /* The window is a child-window to desktop */
NULL, /* No menu */
hInstance, /* Program Instance handler */
NULL /* No Window Creation data */
);



if (!hwnd)
{
MessageBox(NULL, "Call to CreateWindow failed!", "Script Loader v0.1", 0);
return 1;
}

ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);

/* Run the message loop. It will run until GetMessage() returns 0 */
while (GetMessage (&messages, NULL, 0, 0))
{
/* Translate virtual-key messages into character messages */
TranslateMessage(&messages);
/* Send message to WindowProcedure */
DispatchMessage(&messages);
}

/* The program return-value is 0 - The value that PostQuitMessage() gave */
return messages.wParam;
}

/* Controls, Styles, Values*/
HWND button;
static HWND edit;
HFONT ButtonStyle, LabelStyle;
enum {ID_BUTTON = 1, ID_EDIT = 2};

/* This function is called by the Windows function DispatchMessage() */
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT paintStruct;
HDC hDC;

switch (message) /* handle the messages */
{
case WM_CREATE:
button = CreateWindow("Button","Load Script", BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 70, 50, 100, 20,hwnd,(HMENU)ID_BUTTON,g_hInst,0);
edit = CreateWindow("static", "Choose A Script To Run.", WS_CHILD | WS_VISIBLE | ES_READONLY, 53, 5, 175, 20, hwnd, (HMENU)ID_EDIT, g_hInst, 0);
break;

case WM_COMMAND:
switch(wParam)
{
case ID_BUTTON:
{
OpenFileDialog();
Running = CreateThread(0, 0, RunScript, 0, 0, 0);
Checking = CreateThread(0, 0, Check, 0, 0, 0);
break;
}
}
break;

case WM_CTLCOLORSTATIC:
SetTextColor((HDC) wParam, RGB(148, 0, 211)); //PURPLE
SetBkColor((HDC) wParam, RGB(240, 240, 240)); //COLOR_WINDOW
return (LONG) GetStockObject(NULL_BRUSH);
break;

case WM_PAINT:
hDC = BeginPaint(hwnd,&paintStruct);
//HBRUSH NewColor;
//SetTextColor(hDC, RGB(255, 0, 255));
//TextOut(hDC, 50, 42, "Meh", 13);
//NewColor = CreateSolidBrush(RGB(250, 25, 5));
//SelectObject(hDC, NewColor);
//DeleteObject(NewColor);

ButtonStyle = CreateFont(14, 0, 0, 0, FW_DONTCARE, 0, 0, 0, 0, 0, 0, PROOF_QUALITY, 0, ("Arial"));
LabelStyle = CreateFont(15, 0, 0, 0, FW_BOLD, 0, true, 0, 0, 0, 0, PROOF_QUALITY, 0, ("Arial"));

SendMessage(button, WM_SETFONT, WPARAM(ButtonStyle), true);
SendMessage(edit, WM_SETFONT, WPARAM(LabelStyle), true);

DeleteObject(ButtonStyle);
DeleteObject(LabelStyle);
EndPaint(hwnd, &paintStruct);
break;

case WM_DESTROY:
CloseHandle(Running);
CloseHandle(Checking);
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
break;

default: /* for messages that we don't deal with */
return DefWindowProc (hwnd, message, wParam, lParam);
}

return 0;
}


Manifest.rc


//CREATEPROCESS_MANIFEST_RESOURCE_ID RT_MANIFEST "ScriptLoader.exe.manifest"

#define VOS_NT_WINDOWS32 0x00040004L
#define VFT_APP 0x00000001L

1 24 ScriptLoader.exe.manifest

MAIN_ICON ICON MOVEABLE PURE LOADONCALL DISCARDABLE "Icon.ico"


//include version information in .exe, modify these values to match your needs
1 VERSIONINFO
FILEVERSION 1,0,0,0
PRODUCTVERSION 0,1,0,0
FILETYPE VFT_APP
{
BLOCK "StringFileInfo"
{
BLOCK "040904E4"
{
VALUE "CompanyName", "GGzz - SRL C++ Programming"
VALUE "FileVersion", "0.1.0.0"
VALUE "FileDescription", "Loads Scripts"
VALUE "InternalName", "ScriptLoader"
VALUE "LegalCopyright", "I'm A Pirate"
VALUE "LegalTrademarks", ""
VALUE "OriginalFilename", "ScriptLoader"
VALUE "ProductName", "ScriptLoader"
VALUE "ProductVersion", "0.2.0.0"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x0409, 1252 //language codes
}
}
Links:
http://www.multiupload.com/D9A5EMKNCA

noidea
11-30-2011, 10:19 PM
Bump. Seems very cool. Someone should try it to compete with Harry's dirty crashing method.

tls
12-01-2011, 09:50 PM
This seems like a cool idea but I can't actually get it to do anything.

Brandon
12-01-2011, 10:50 PM
This seems like a cool idea but I can't actually get it to do anything.


Did u compile it? or are u using the exe that was in the bin folder?

When u click the button, u choose ur script and it opens it in simba. I tried it with pest control script and it opens every time, when it says "Successfully executed in the debug box, then it restarts everything again.

Note: My simba is installed at C:/Simba the program above goes to c:/simba/simba.exe + your script location from the openfile dialog.

Tried it on four scripts just now.. One is a reflection script, other is pest control, other is shuttle vine vanquisher and the other is narcle fast fighter.

12154

tls
12-01-2011, 11:32 PM
I compiled it myself the first time, then used the bin.

Brandon
12-01-2011, 11:39 PM
I compiled it myself the first time, then used the bin.

Hmm I just re-upped the whole project.. my friend couldn't get it to run because he didn't have libgcc.. so I linked all the libraries statically and re-upped the project. Now he has it running.

Does it even run for u? Does it open simba? Does it start a script? Where does it get stuck?

tls
12-01-2011, 11:40 PM
It would load up the window, but never simba. It must be my simba location.

Brandon
12-01-2011, 11:45 PM
It would load up the window, but never simba. It must be my simba location.


Hmm I just found a bug which I'll fix in a sec.. It will load .simba scripts.. but not .Simba scripts.. Note the capital S.. damn c++ is so picky on case sensitive stuff.. :c

Edit: Just updated it to detect smart applet declaration error which has been happening quite a lot lately!

Edit2: Going to update it to detect the location of Simba.exe automatically.. whether it be on a flashdrive or not.. Example:

{DriveHere} :/Simba/{0 - any amount of folders here}/Simba.exe

Smartzkid
01-13-2012, 02:18 AM
Placeholder so I remember to read your code.

Beautiful code, dude! Very impressive. /placeholding.

Brandon
01-13-2012, 02:32 AM
Haha Thanks I tend to live in the C++ forums.