2

I have written a program which triggers a relay switch on a serial port. The relay is closed for 10ms, after which the program closes. However, the program insists on running in a small command prompt window. I would like the program to run without stealing focus; either by running in the background or, even better, without opening a window at all.

Here is the complete program:

#include <windows.h>

//Initialise Windows module
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance,
LPSTR lpszArgument, int nFunsterStil)
{
 //Define the serial port precedure
 HANDLE hSerial;

 //Open the port
 hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

 //Switch on relay
 EscapeCommFunction(hSerial, SETDTR);

 //Wait 10ms
 Sleep(10);

 //Switch off relay
 EscapeCommFunction(hSerial, CLRDTR);

 //Close the port
 CloseHandle(hSerial);

 //End with error code 0
 return 0;
}

What must I change in order to prevent it running in a window?

2
  • Have you tried to start the program with yourapp.exe /NOCONSOLE parameter? Commented Nov 1, 2011 at 15:52
  • Tried that - it doesn't work :( Commented Nov 1, 2011 at 16:05

2 Answers 2

5

Try adding

#pragma comment(linker, "/SUBSYSTEM:WINDOWS")

If that does not work try to hide the window manually:

HWND hWnd = GetConsoleWindow();
ShowWindow( hWnd, SW_HIDE );
Sign up to request clarification or add additional context in comments.

8 Comments

I've added this under the #include <windows.h>, with no luck.. The program still runs in a window :(
How do you run your program? Are you starting it manually (i.e. clicking on an icon) or do you call it from within another program? If you start it from within another program, you may want to look at this codeproject.com/KB/winsdk/runsilent.aspx
What header do I need to include to define the routines you have used in your second suggestion?
You just need the windows.h. You might have not defined the correct version for target OS so you don't get everything when you include it. Try adding this before including windows.h: #define _WIN32_WINNT 0x0500
ShowWindow has been in Windows since 2.0 at the latest, and I think GetConsoleWindow came in with Win95, if not NT 3.1. The _WIN32_WINNT define should be unnecessary.
|
0

What type of project did you create? If you selected console application, the compiler is doing it. Make an empty Win32 application with the above source. No window should be created. If it is, consider how you're launching the application (start, cmd /c, etc)

1 Comment

Yep you are right. That's basically what my #pragma was supposed to fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.