Home ProgrammingC# Programming: Tips & Tricks (Part I)

Programming: Tips & Tricks (Part I)

by Kliment Andreev
2 comments
Reading Time: 2 minutes

pass variables between two forms in Visual C++

This example will show you how to pass variables between two forms in Visual C++. We’ll create two forms, drop a button and a text box on the first form and a label box on the second form. When we start the program, we can type something in the text box. Once we click the button, the second form will show up with the label containing the text from the text box that’s on the first form.
First, let’s create a project in VC++ 2008. Click File | New, then Visual C++ and then Windows Forms Application. From the Toolbox, drag and drop, a button and a text box. Next, from the Solution Explorer on the right, right-click the name of your project, choose Add, New Item and then Windows Form. When the second form appears, drag and drop a label on the form. Save all files. Open the source for the first form (probably Form1.h) and right after the #pragma statement insert:

#include "Form2.h"
// Make sure that the source file name is correct

Then, switch to the design mode for the first form, double-click the button control and put the following lines between the brackets. This is an event-handler that runs when the button is clicked.

Form2^ newform = gcnew Form2;
newform -> strSomething = textBox1->Text
if (newform->ShowDialog(this) == ::DialogResult::OK) delete newform;

Switch to the source of the second form and define the string strSomething as shown. That’s the variable that we are using to pass values.

public:
		Form2(void)
		{
			InitializeComponent();
			//
			//TODO: Add the constructor code here
			//
		}    

		        String^ strSomething;

	protected:
		///

Now, switch to the desing mode of the second form, double-click anywhere on the form to invoke the event-handler that runs when the form is loaded. Here, insert the following statement.

label1->Text = strSomething;

As you can probably see, we created the second form with an extra parameter of string type. When we created this form within the source of the first form, we passed the value of textBox1 to that parameter and then in the second form, we take that value and assign it to the label. We can’t use something like this:

newform->label1->Text = textBox1->Text;

That’s because label1 is a private member of the Form2 class and strSomething is a public member.

System uptime – Visual C++ utility

It’s been a while when I was programming in C, maybe more than 15 years. I decided to refresh my memory and create a small console application that will give me the system uptime and the date and time when the OS was installed. This small app should work on all platforms after Windows 2000.

I used Visual C++ 2008 and this program compiles without any errors or warnings. While I was browsing for the solutions implemented in this program, I found that some of the proposed solutions won’t compile on VC 2008.

Start VC2008, choose File | New | Project. For Project Types choose Win32 and then Win32 Console Application. You can copy and paste the whole source below. This is a simple console application and there are no extra header files or any resource files. You can also, download the executable that’s attached.

#include "stdafx.h"
#include <windows.h>       

char* GetUptime()
{
   int tickCount, nTime[5];
   static char szUptime [1000];
   tickCount = GetTickCount();
   nTime[0] = tickCount / 1000 % 60; // Seconds
   nTime[1] = tickCount / 1000 / 60 % 60; // Minutes
   nTime[2] = tickCount / 1000 / 60 / 60 % 24; // Hours
   nTime[3] = tickCount / 1000 / 60 / 60 / 24 % 7; // Days
   nTime[4] = tickCount / 1000 / 60 / 60 / 24 / 7 % 52; // Weeks
   memset(szUptime, 0, sizeof(szUptime));       

   for(int i = 4; i >= 0; i--)
   {
      char* szLabel;
      char tmpUptime[3];       

      if (i == 4) (nTime[4] > 1 || nTime[4] == 0) ? szLabel = " Weeks, " : szLabel = " Week, ";
      else if (i == 3) (nTime[3] > 1 || nTime[3] == 0) ? szLabel = " Days, " : szLabel = " Day, ";
      else if (i == 2) (nTime[2] > 1 || nTime[2] == 0) ? szLabel = " Hours, " : szLabel = " Hour, ";
      else if (i == 1) (nTime[1] > 1 || nTime[1] == 0) ? szLabel = " Minutes, " : szLabel = " Minute, ";
      else if (i == 0) (nTime[0] > 1 || nTime[0] == 0) ? szLabel = " Seconds" : szLabel = " Second";
      memset(tmpUptime, 0, sizeof(tmpUptime));
      _itoa_s(nTime[i], tmpUptime, 3, 10);
      strcat_s(szUptime, 1000, tmpUptime);
      strcat_s(szUptime, 1000, szLabel);
      }       

   return szUptime;
}       

char* GetInstalled()
{
   HANDLE hFile;
   WIN32_FIND_DATA FileInformation;
   SYSTEMTIME st;
   char tmpChar[12];
   char* month = "";
   char* comma = ", ";
   char* space = " ";
   char* colon = ":";
   TCHAR winDir[MAX_PATH];
   static char szInstalled[1000];
   GetWindowsDirectory(winDir, MAX_PATH);
   hFile = ::FindFirstFile(winDir, &FileInformation);
   FileTimeToSystemTime(&FileInformation.ftCreationTime, &st);
   switch (st.wMonth)
   {
      case 1:
      month = "January ";
      break;
      case 2:
      month ="February ";
      break;
      case 3:
      month = "March ";
      break;
      case 4:
      month ="April ";
      break;
      case 5:
      month = "May ";
      break;
      case 6:
      month ="June ";
      break;
      case 7:
      month = "July ";
      break;
      case 8:
      month ="August ";
      break;
      case 9:
      month = "September ";
      break;
      case 10:
      month ="October ";
      break;
      case 11:
      month = "November ";
      break;
      case 12:
      month ="December ";
      break;
      default:
      break;
   }       

   strcat_s(szInstalled, 1000, month);
   _itoa_s(st.wDay, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, comma);
   _itoa_s(st.wYear, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, space);
   _itoa_s(st.wHour, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, colon);
   _itoa_s(st.wMinute, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   strcat_s(szInstalled, 1000, colon);
   _itoa_s(st.wSecond, tmpChar, 12, 10);
   strcat_s(szInstalled, 1000, tmpChar);
   return szInstalled;
}
int _tmain(int argc, _TCHAR* argv[])
{
      char* upTime;
      char* installed;
      printf("%s\n", "-----------------------------------------------------------------");
      printf("%s\n", "KInfo v0.1 -- Program by Kliment Andreev -- Public Domain -- 2009");
      printf("%s\n", "-----------------------------------------------------------------");
      upTime = GetUptime();
      printf("%s%s"," System Uptime: ", upTime);
      installed = GetInstalled();
      printf("\n%s%s\n","System Installed: ", installed);
      return 0;
}

kinfo2

Enumerating files and folders in Visual C++

This is a program that will enumerate all files, folders and sub-folders under a given folder. Folders with no access will be skipped and an *ERROR* message will be recorded on the console. Attached is the executable file (link at the bottom).

#include "stdafx.h"    

using namespace System;
using namespace System::Collections;
using namespace System::IO;    

int main(array ^args)
{
	array^ strSubFolders = gcnew array(20);
	array^ strFiles = gcnew array(20);
	Stack^ objFolders = gcnew Stack;
	Object^ objItem;
	String^ strSourceFolder;
	String^ strCurrentFolder;
	String^ strEachFile;
	String^ strEachFolder;
	String^ strArgs;
	int ArgsCounter=0,
		FileCounter=0,
		FolderCounter=0,
		ErrorCounter=0;    

	for each (strArgs in args) ArgsCounter++;    

	if (ArgsCounter==0) {
		Console::WriteLine("Usage: eff , enumerates all files and folders under ");
		Console::WriteLine("Public domain - Program by Kliment Andreev, 2009");
		return 0;
	}    

	strSourceFolder = args[0];    

	if (!System::IO::Directory::Exists(strSourceFolder)) {
		Console::WriteLine("Folder doesn't exist!");
		return 0;
	}    

	objFolders->Push(strSourceFolder);	    

	while (objFolders->Count > 0) {
		objItem = objFolders->Pop();
		strCurrentFolder = safe_cast(objItem);
		Console::WriteLine("{0}",strCurrentFolder);    

		try {
			strSubFolders = Directory::GetDirectories(strCurrentFolder);
			strFiles = Directory::GetFiles(strCurrentFolder);    

			for each (strEachFile in strFiles){
				FileInfo^ fi = gcnew FileInfo(strEachFile);
				Console::WriteLine("{0}\\{1} ",fi-&gt;DirectoryName,fi->Name);
				FileCounter++;
			}    

			for each (strEachFolder in strSubFolders) {
				objFolders->Push(strEachFolder);
				FolderCounter++;
			}    

		}    

		catch(System::Exception ^ex) {
			Console::WriteLine("*ERROR* {0}",ex->Message);
			ErrorCounter++;
		}
	}    

	Console::WriteLine("\nTotal: {0} files, {1} folders and {2} errors.", \ 
FileCounter, FolderCounter, ErrorCounter);    

    return 0;
}

eff

2 comments
0

Related Articles

2 comments

Winton April 15, 2014 - 12:53 PM

Hi Dude, I’m a bit of a Visual C++ novice, but I mostly understand your post. There appear to be few bits of HTML code showing that shouldn’t, and I’m wondering if they are causing me enough confusion not to get the code shown working. I don’t see an error message though – just the second form doesn’t load. Any chance you can clearup the HTML?
Regardos,
Winton.

Kliment Andreev April 15, 2014 - 8:54 PM

I had some old HTML tags.

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More