Category > C/C++

Mouse Prank in C++

» 07 July 2012 » In C/C++, Programming » 3 Comments

Hooray for the new post. This post was actually a draft way back 2011. But hopefully, i’ll be motivated and keep on posting. I have many tricks to share!

Several years ago, me and my mates were having fun writing prank codes. I can barely remember them all, but here’s one.

One of the main reason why to code is fun. Of course, we all do want to have some fun. I’ll show and explain how to write a simple C++ program that will add weight to the cursor, making it difficult to use. Here’s the function that does the trick:

void heavyCursor(int weight) {
	POINT cPos;

	while (1) {
		GetCursorPos (&cPos);
		int x = cPos.x;
		int y = cPos.y;

		y += weight;

		SetCursorPos(x,y);
		Sleep(5);
	}
}

To clarify, yes it is an endless loop. This code will continually add points in the y axis and resets the cursor position in the screen. This will be fun, but very hard to stop. Sometimes it’s fun watching your friend struggle on reaching Task Manager just to stop this little program.

Continue reading...

Tags: , , ,

Victories, and Beyond

» 25 January 2011 » In C/C++, Life, Programming » 1 Comment

This time, I will be less technical. No, actually ignore the first sentence. I’ve been coding since 2007, and C was my first language. I use Turbo C back then, and it was a pretty cool compiler back then. It’s now an antique, and you can download it here.

As I was saying, I can still remember the things I’ve been coding in Turbo C. I had that Pythagorean solver, which I posted in planet-source-code. I was so proud, and I even created a general mathematical solver, for a bigger one. Oh, and do you know that I tYpE LiKe tHiS bEfoRe?. Anyway, why am I saying all this stuff? Actually I was just refreshing my memory of what I am before, and comparing it on what I am now.

For the times that have passed, coding became an art for me. It sounds silly, but true. I can safely say I’ve done more than 100 usable programs and scripts just to fulfill my hobby. I used to code for automation, and exploitation. Nobody in my family knows what I’m doing. All they can see, is me, looking at a computer screen for an average of 16+ hours a day. I never felt boredom in coding, as boredom comes when you’re out of ideas on what to code. My ideas are hard to implement. Sometimes thoughts have been passing though my brain in countless numbers of times.

So what did I do to be, here? Almost 4 years of programming experience, I never kept track of myself. Though I somewhat became a little boastful, it has changed. August, last year, I wiped out my old HDD, desperately (see my other post). Alongside with that, is the memories, and codes of my past. So basically I never got to see those stuff again, ever. On the good side, change.

Change is inevitable, this is what I hear from others. I usually, don’t care, but now it’s the opposite. Simple things change, and these leads to greater changes. And you know what? Learning a new language, changes me. When I’m introduced to C++, I was discouraged by a friend in UK. Thinking the iostream library is a bloat, I embraced the C Standard Library. Until one day, I just realized I need to go for C++.

C++ is the superset of C, and as I became open to the object oriented environment, I became open to a new environment in real life as well. Though, I do not wish to put things in detail, I can simply say that this is one of the most remarkable changes in me. And praise God for that.

Few hours ago (January 25, 2010), I won a regional C++ programming competition. Before the awarding, I was shaking because of the cold air + the excitement I felt. This, is what I can call “Victory”. And even if I lose, it still is a victorious fight. I was very grateful for what God has made me. I started this year with a brand new prayer life. And these victories I’ve been experiencing, is a way of God telling me.. “There’s more..“.

It’s not only victories that I should prepare for, failures and discouragements will arise. But, faith will still remain. And if I fall, I fall forward, plus, God will catch me. God bless.

Continue reading...

Tags: , , , , ,

Upscreen: A Screenshot Utility using the Min.us API

» 31 December 2010 » In C/C++, Open-Source, Programming, Releases » 3 Comments

It’s been a long time since I posted something, again. Well actually I was hospitalized for 6 days, from December 18 to 24. I nearly spent Christmas the hospital. And after the hospital days, I worked on 2 projects, one is paid, and the other one is this.

The Story

Min.us is a great image hosting website. And when the time they sent me their API (I asked; their API wasn’t public yet that time) I came up with an idea, and yes basically the idea is to upload the screenshot taken in a computer to the min.us image hosting. When I finished the first (paid) project, I switched to this one. And I started with finding a way to execute code when the user pressed the PrintScreen key. I thought of using Windows Hooks but later on, I found out about RegisterHotKey and used it instead. But there’s a little problem, when I registered PrintScreen as a hotkey. Just like:

RegisterHotKey(NULL, 1, NULL, 0x2C);

The normal function of the key is disabled. This is bad, and I probably really need to use a keyboard hook instead. But no, instead I changed the hotkey and set it to Win + PrintScreen.

RegisterHotKey(NULL, 1, MOD_WIN | MOD_NOREPEAT, 0x2C);

So yes, it’s working great now. Though the PrintScreen key must be pressed first to load the image to the clipboard. So if you’re going to upload a screenshot, Press PrintScreen, then Win + PrintScreen. The good thing caused by this is, you can choose what to upload, and just place it in your clipboard. Say you need to upload an image from the internet, copy it, and then press Win + PrintScreen. Sweet.

Next, I need to get the data from the clipboard, and that was easy using GetClipboardData. Then, I need to save the bitmap file from the clipboard. I had some trouble finding a way to do this, so I used a function named CreateBMPFile and CreateBitmapInfoStruct. Success, now originally I was planning to use the BMP image and upload it right away. Then I just realized, the BMP file generated was uncompressed. So I think I need to use PNG instead (No not JPG, never). For this conversion I did some research. I ended up on using the ATL image header, and the CImage class. Well basically, converting an image is just 3 lines:

void Upscreen::ConvertToPNG(LPTSTR &sourceName, LPTSTR &destName) {
	CImage img;
	img.Load(sourceName);
	img.Save(destName);
}

Now that I have my PNG image, its time to upload it. By this time, Min.us have their API published and you can view it here. I only used two methods, CreateGallery and UploadItem. And I created a C++ class for the API:

class Minus {
public:
	std::string editorId, id, readerId;

	Minus();
	virtual ~Minus();
	void CreateGallery();
	void UploadItem(std::string&);

private:
	std::string key;
};

It’s incomplete, because the other two methods wasn’t included. So basically we need to get the editor_id, reader_id, and key from the first method then use these variables on the second method. To get these variables, an HTTP GET request must be accomplished. I do not want to use too much external libraries, so I just used Winsock2. I didn’t have too much trouble performing this, and the only issue I had was separating the HTTP headers from the response body. And later on, I found out its very easy:

response = response.substr(response.find("\r\n\r\n"));

The API’s response content type is JSON. I found it hard finding a good JSON parser in C++. And I ended using JSON Spirit . The downside is, this uses Boost Headers, so both must be downloaded.

I got the variables I need, now to the HTTP POST request. This is the bloodiest part of the program. I had trouble reading the the PNG file, and used ReadFile instead. Then, I didn’t know std::string is not suitable for storing binary data. So after switching many data types, I finally decided to use just a char * pointer to hold the data. And to pass the data, I put the POST headers and the data to a std::vector variable. All went well, but I’m a having 404 error in the POST request, and the data is incomplete. I just figured out the example URL in the Min.us API documentation is wrong. The trailing slash after UploadItem is causing the 404 error, and removing it fixed the problem. The other one was caused by the Content-Length parameter. I used WireShark and LiveHTTPHeaders to trace the packets and again, some bloody debugging. Later on, I found out the number I’ve been passing exceeded by one. After this part, all went so easy. The only thing I have to deal with is validation. Whenever the clipboard has data other than an image, it crashes. So I just placed an if condition to check if the PNG data exist. Because no PNG data will be saved if there’s no valid bitmap file present.

After uploading, I used the editor_id variable and attached it to the min.us URL. And made the program open it at the default browser using ShellExecute.

Header Files

The header files I used in this project are:

#include <WinSock2.h>
#include <windows.h>
#include <atlimage.h>
#include <string>
#include <json_spirit\json_spirit_reader_template.h>

Source Code

The source code is released under the GNU GPL v3. Get it here.

Year Ends

So this became my last post for 2010. Very timely, isn’t it? Anyway, Happy New Year!

Continue reading...

Tags: , , , , , ,

Tran: Get Rid of those Old Archives

» 30 November 2010 » In C/C++, Open-Source, Programming, Releases » 1 Comment

If you download stuff from the internet (especially archived files) a lot, then this will help you clean your mess. Most of us (yes including me), caused by too much excitement of the just-finished-download, will ignore archive files after extracting them. Plus, only few people know how to group their downloads by file-type. Tendency is, to mess up the whole download directory. Of course not all archives there are extracted, but checking them manually is too much pain.

So What’s Tran?

Basically, Tran is a small C++ program that removes extracted archives, and get rid of them for good. Meaning, it will automatically check if an archive is already extracted or not on same directory. That reason this came to my mind is, I myself has a messy download directory. I have too many archive files, and they’re not next to each other so I can’t delete them all at once. Then I decided to work on this C++ program that will do the job for me. I can say it’s fully working because I’ve tested it.

Consequences

If you don’t want to clean your directory, or you prefer your archives to stay, you might have a very large diskspace. Actually, from my folder, I freed up 1.4GB or data. Yeah, it’s not that large, but it’s not small either.

Imagine for 5 years you’re downloading data, and you never get to clean your directory. For every archive your extracted, multiply their size by two, plus the extra size from the compression. And what will you get? Useless files eating up your diskpace. Ok, I know I shouldn’t have used the word useless but the fact that you already used the archive only once by extracting, makes it useless.

Source Code

Of course, the source code is freely available on github. It’s under GPL and fork it if you want. I want to implement new features so I hope you can help me with that. Also, leaving a comment or suggestion would be nice.

Continue reading...

Tags: , , , , , ,

Why Use Pointers?

» 22 November 2010 » In C/C++, Programming » 4 Comments

This is a very much asked questions, especially among students. Pointers, at first, is very hard to understand. All those asterisks * and ampersands & and the crazy assignments. Well, I assume you already understand pointers, or rather, you have a an idea how generally pointers operate. Then you might wanna ask, why use pointers?

Pointers Reviewed

As we all (should) know, pointers stores the address of a variable. So basically, when we call a pointer by name, we’re referring to the address. Let’s take this for example:

int *p1

The above declarations tell the compiler that p1 is a pointer to an integer. Means that you cannot assign an address of a character or a floating point to it. Actually you might want to try, but basically you’re just wasting time. Anyway, let’s say we have this variable a with the value of 5. And then we do this:

p1 = &a

We just assigned the address of a to the pointer p1. So if we are to print p1 it’s just like, we’re printing the value of &a which is the address of a. So how do we know that its the address of a? Answer: the ampersand &.

Accessing Values with Pointers

So on the above review example, we assigned &a to p1. But what if we are to access the value of a using pointers? Normally we access some variables value by its name. But now, since we are using pointers, we are going to access the value by the variable’s pointer. Say for example, we are to print the value of a. Normally we will do:

std::cout << a;

But if we are to use pointers, we do this:

std::cout << *p;

Remember, we assigned the address of a to p1, and if we are to access the value of a with a pointer, we use the asterisk * symbol, like *p1.

Now, to make it less confusing, let’s say we do not have any pointers. And we have &a as the address of a. To access its value, we have to use the asterisk symbol, and it should be like *&a. Still confused? I guess not.&a here is our reference to the value of a, and by using an asterisk, we dereferenced it. Making an asterisk * a Dereference Operator.

Using Pointers in Functions

Whenever we pass variables to a function, let’s say main called the function nUpdate(); which accepts 2 parameters, one is a variable of type int to be updated, and the other one is the constant integer to be added to the variable. Normally the function cannot directly alter the variable that will be passed to it, instead it will copy the variable and create another one with the same attributes and just return it to the main function. Here’s how it will look like:

int nUpdate(int a, const int b) {
    return a + b;
}

int main() {
    int a = 5;
    a = nUpdate(a, 6);
    return 0;
}

After main called nUpdate() the value of a now is 11. Am I right? Now, this is correct. But, there’s another way. Without wasting some bits, we can just directly update a in the function. How? Pointers. Now, this is one major use of pointers, and I’ll explain it further later. Using pointers, we are going to pass just the address of our variable a and the constant. So we have to make changes, on the parameter type of the function, and we need something that holds addresses. Ah, pointers.

int nUpdate(int *p, const int b) {
    *p += b;
}

int main() {
    int a = 5;
    nUpdate(&a, 6);
    return 0;
}

There we have it. We passed the address of a which is &a, and the pointer called p receives the address, and we accessed it by using our dereference operator * just like what we did earlier. Now there’s another way of doing the very same thing, except we will not be directly using a pointer. If you can remember earlier, and using our latest example, pointer p holds the address of a which is &a. So, we can do this:

int nUpdate(int &a, const int b) {
    a += b;
}

int main() {
    int a = 5;
    nUpdate(a, 6);
    std::cout << a;
    return 0;
}

This approach, is what I use. As you can see, our function now accepts an address of an integer variable. And in our main, we passed the variable a. But from the function’s point of view, instead of receiving the value of a, it grabs its address. And to access the value of that address we again should use the dereference operator *, and *&a is equal to a.

A Larger View

The past examples showed how useful pointers are in functions. But to show you more of its importance, look at a bigger view. Say there’s this large program, its main calls some function and passes loads of data, say millions of bytes (MB). Without the use of pointers, this is heavy. As the function will copy all those data to its scope in memory, and do its job. It will increase memory usage to be short. Now with the help of pointers, the function could just get the address of all those variables which holds the data and do its job. No copying, less memory usage.

Moving On

I surely hope that this is very clear for you now, if you are still confused, then C/C++ is not your type. Anyway, learning takes time and good luck with pointers!

Continue reading...

Tags: , , , ,

Least but Best

» 15 November 2010 » In C/C++, Life, Programming » 1 Comment

This morning, we had a laboratory exercise in my algorithm’s class. There are two (2) sets of problems, and we must draw the flowchart in Visio, and code it in C++. The first problem is tricky, while the second one is very easy (so I won’t mention it here). Here’s what the problem says:

Make the user input 3 integers, and determine which has the least value.

Ok, this sounds very easy. Come to think of it, it is. Well, actually it asks for the variable with the least integer value. So a simple if-else statement won’t do. By the way, my flowchart is already done, and it was so messy. There are 14 pairs of On-Page Connectors (makes it 28 ‘A’-'N’ circles), good thing I didn’t upload it so you can’t see how bad it is. Heh.

Anyway, on a normal if-else statement, its not hard. Here’s what it should look like:

#include <iostream>

template <class T>
void rcin(T &input) {
	std::cin >> input; 
	std::cin.ignore();
}

int main () {
	int a, b, c;
	std::cout << std::endl
		      << "\tEnter 3 numbers:" << std::endl
			  << std::endl
			  << "\t\tA) "; rcin(a);
	std::cout << "\t\tB) "; rcin(b);
	std::cout << "\t\tC) "; rcin(c);
	std::cout << std::endl;
	if (a == b && b == c) {
		std::cout << "\tAll numbers are equal.";
	} else if (a == b) {
		if (c < a) {
			std::cout << "\tC has the integer with the least value: " << c;
		} else {
			std::cout << "\tA and B has the integer with the least value: " << a;
		}
	} else if (b == c) {
		if (a < b) {
			std::cout << "\tA has the integer with the least value: " << a;
		} else {
			std::cout << "\tB and C has the integer with the least value: " << b;
		}
	} else if (a == c) {
		if (b < a) {
			std::cout << "\tB has the integer with the least value: " << b;
		} else {
			std::cout << "\tA and C has the integer with the least value: " << a;
		}
	} else if (a < b) {
		if (c < a) {
			std::cout << "\tC has the integer with the least value: " << c;
		} else {
			std::cout << "\tA has the integer with the least value: " << a;
		}
	} else if (b < c) {
		std::cout << "\tB has the integer with the least value: " << b;
	} else {
		std::cout << "\tC has the integer with the least value: " << c;
	}
	std::cin.get();
	return 0;
}

NOTE: Nevermind my rcin() function for now, I’ll discuss that on my future post.

So yeah, it’s bad for the eyes. But it works fine, though, the answer is simpler and easier to understand. I just need to pull things out of my head, and not focus on the flowchart. We had this rule of Resist the temptation to code. And to be honest, I can’t follow it. My mind works better if I’m in front of an IDE or editor. Anyway here’s my solution:

#include <iostream>
#define SIZE 3

template <class T>
void rcin(T &input) {
	std::cin >> input; 
	std::cin.ignore();
}

int main () {
	int nums[SIZE], smallest, var;
	std::cout << std::endl
		      << "\tEnter 3 numbers:" << std::endl
			  << std::endl;
	for (int i = 0; i < SIZE; i++) {
		std::cout << "\t\t" << i + 1 << ") ";
		rcin(nums[i]);
		smallest = (i == 0) ? nums[i] : (nums[i] < smallest) ? nums[i] : smallest;
	}
	std::cout << std::endl
			  << "\tThe smallest value is " << smallest << std::endl;
	std::cin.get();
	return 0;
}

I used nested shorthand if statements to make it simpler. And about the function, nevermind it and use std::cin instead. It was just my practice.

Anyway, that’s how simple it is. And from that, I will create a flowchart. Heh. That’s how my mind works.

Continue reading...

Tags: , , , ,