Related
I've put two arrows in the code to identify the areas I will speak about
I'm trying to add a button to a C++ window thing, the Visual Studio automatically put a whole bunch of code I can't understand into the program for me, I'm coming from C# .NET Windows forms so this is already extremely confusing and now that I've had some kind of idea how to add the button I can't find the parent window and I've tried a whole bunch of different words I find around the place in the code and nothing is working, I don't even know if I'm in the right place, I don't even know what to look up, this entire bunch of code is 100% confusing, I understand none of it.
I just want a small little program that just works on all computers with or without .Net and supposedly I can have the libraries built into this exe that this will compile so I can run it on a PC with nothing installed supposedly. If there is a way to do that with C# I would love to hear about it, I made the program in C# and it doesn't work on my work laptop, just won't start and I'm assuming it's because the work laptop doesn't have .NET stuff on it.
// Stock Taking C.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "Stock Taking C.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_STOCKTAKINGC, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_STOCKTAKINGC));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_STOCKTAKINGC));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_STOCKTAKINGC);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_CREATE: {
This is me trying to add a button <----------- LOOK HERE
HWND hwndButton = CreateWindow(
L"BUTTON",
L"OK",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
10,
10,
100,
100,
m_WndProc, <-- this bit keeps being all like invalid and I can't find the parent bit
NULL,
(HINSTANCE)GetWindowLongPtr(m_hwnd, GWKO_HINSTANCE),
NULL);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
WndProc() is the message procedure for the window that is created in InitInstance(). Thus, the HWND that is passed to WndProc() is that same window. So, since you are handling that window's WM_CREATE message, use that window as the parent for the button, eg:
HWND hwndButton = CreateWindow(
L"BUTTON",
L"OK",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
10,
10,
100,
100,
hWnd, // <-- parent window
NULL,
(HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE), // <-- or the global hInst variable initialized by InitInstance()
NULL);
I have a button which is subclassed and I would like it to display a bitmap with a transparent background. Upon searching the internet, I found that you have to do it with the function AlphaBlend( I tried this but that didn't work either). I also saw this bitmap transparency in Visual Studio 2013 C++ thread and I tried the steps but I couldn't do it. I would be fine with either GDI or GDI+ just as long as i can get button with a transparent background image on it.
Example:
Here is my code—— I know it's messy but please bare with it as I was trying a lot of things to try and make it work (there was a lot of copying and pasting)
Update : Here is the code again but trimmed without all the fat and yes I did try WS_EX_LAYERED on both the windows.
// CustomButton2.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "CustomButton2.h"
#include <commctrl.h>
#include <gdiplus.h>
#include <system_error>
#include "SkinClass/skin.h"
#define MAX_LOADSTRING 100
#define CRAPPY 567
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' " "version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
const char g_szClassName[] = "MyClassName";
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
void RegisterClass1(HINSTANCE);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
/// Turn given window into a layered window and load a bitmap from given resource ID
/// into it.
/// The window will be resized to fit the bitmap.
/// Bitmap must be 32bpp, top-down row order, premultiplied alpha.
///
/// \note For child windows, this requires Win 8 or newer OS
/// (and "supportedOS" element for Win 8 in application manifest)
///
/// \exception Throws std::system_error in case of any error.
void SetLayeredWindowFromBitmapResource(
HWND hwnd, UINT bitmapResourceId, HINSTANCE hInstance = nullptr)
{
// Enable "layered" mode for the child window. This enables full alpha channel
// transparency.
// GetWindowLong() won't reset the last error in case of success.
// As we can't judge from the return value of GetWindowLong() alone if
// the function was successful (0 may be returned even in case of
// success), we must reset the last error to reliably detect errors.
::SetLastError(0);
DWORD exStyle = ::GetWindowLong(hwnd, GWL_EXSTYLE);
if (!exStyle)
{
// NOTE: Call GetLastError() IMMEDIATELY when a function's return value
// indicates failure and it is documented that said function supports
// GetLastError().
// ANY other code (be it your own or library code) before the next line
// must be avoided as it may invalidate the last error value.
if (DWORD err = ::GetLastError())
throw std::system_error(static_cast<int>(err),
std::system_category(),
"SetLayeredWindowFromBitmapResource: Could not get extended window style");
}
// SetWindowLong() won't reset the last error in case of success.
// As we can't judge from the return value of GetWindowLong() alone if
// the function was successful (0 may be returned even in case of
// success), we must reset the last error to reliably detect errors.
::SetLastError(0);
if (!::SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED))
{
if (DWORD err = ::GetLastError())
throw std::system_error(static_cast<int>(err),
std::system_category(),
"SetLayeredWindowFromBitmapResource: Could not set extended window style");
}
// Use RAII ( https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization )
// to cleanup resources even in case of exceptions.
// This greatly simplifies the code because now we don't have to manually cleanup the
// resources at every location in the code where we throw an exception.
struct Resources {
HBITMAP hImage = nullptr;
HGDIOBJ hOldImage = nullptr;
HDC hMemDC = nullptr;
// This destructor will be automatically called before the function
// SetLayeredWindowFromBitmapResource() returns aswell as any locations
// in the code where the "throw" keyword is used to throw an exception.
~Resources()
{
if (hMemDC)
{
if (hOldImage)
::SelectObject(hMemDC, hOldImage);
::DeleteDC(hMemDC);
}
if (hImage)
::DeleteObject(hImage);
}
} res;
// Make it possible to use nullptr as an argument for the hInstance parameter of
// this function. This means we will load the resources from the current executable
// (instead of another DLL).
if (!hInstance)
hInstance = ::GetModuleHandle(nullptr);
// Load bitmap with alpha channel from resource.
// Flag LR_CREATEDIBSECTION is required to create a device-independent bitmap that
// preserves the alpha channel.
res.hImage = reinterpret_cast<HBITMAP>(::LoadImage(
hInstance, MAKEINTRESOURCE(bitmapResourceId), IMAGE_BITMAP,
0, 0, LR_CREATEDIBSECTION));
if (!res.hImage)
{
DWORD err = ::GetLastError();
throw std::system_error(static_cast<int>(err),
std::system_category(),
"SetLayeredWindowFromBitmapResource: Could not load bitmap resource");
}
// Get bitmap information (width, height, etc.)
BITMAP imgInfo{ 0 };
if (!::GetObject(res.hImage, sizeof(imgInfo), &imgInfo))
{
DWORD err = ::GetLastError();
throw std::system_error(static_cast<int>(err),
std::system_category(),
"SetLayeredWindowFromBitmapResource: Could not get bitmap information");
}
if (imgInfo.bmBitsPixel != 32 || imgInfo.bmPlanes != 1)
{
// Use a constant error value here because this is our own error condition.
// Of course GetLastError() wouldn't return anything useful in this case.
DWORD err = ERROR_INVALID_DATA;
throw std::system_error(err, std::system_category(),
"SetLayeredWindowFromBitmapResource: bitmap must be 32 bpp, single plane");
}
// Create a memory DC that will be associated with the image.
// UpdateLayeredWindow() can't use image directly, it must be in a memory DC.
res.hMemDC = ::CreateCompatibleDC(nullptr);
if (!res.hMemDC)
{
DWORD err = ::GetLastError();
throw std::system_error(static_cast<int>(err),
std::system_category(),
"SetLayeredWindowFromBitmapResource: Could not create memory DC");
}
res.hOldImage = ::SelectObject(res.hMemDC, res.hImage);
if (!res.hOldImage)
{
DWORD err = ::GetLastError();
throw std::system_error(static_cast<int>(err),
std::system_category(),
"SetLayeredWindowFromBitmapResource: Could not select bitmap into memory DC");
}
// Assign the image to the child window, making it transparent.
SIZE size{ imgInfo.bmWidth, imgInfo.bmHeight };
POINT ptSrc{ 0, 0 };
BLENDFUNCTION blend{ AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
if (!::UpdateLayeredWindow(hwnd, nullptr, nullptr, &size, res.hMemDC, &ptSrc,
0, &blend, ULW_ALPHA))
{
DWORD err = ::GetLastError();
throw std::system_error(static_cast<int>(err),
std::system_category(),
"SetLayeredWindowFromBitmapResource: Could not update layered window");
}
// Destructor of res object will cleanup resources here!
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
RegisterClass1(hInstance);
HWND hWnd = CreateWindowExA(WS_EX_LAYERED, g_szClassName, "Scenes", WS_OVERLAPPEDWINDOW | WS_EX_LAYERED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
hInstance, NULL);
HWND hButton = CreateWindow(TEXT("BUTTON"), TEXT("START EDITING!"), WS_CHILD | WS_VISIBLE | BS_OWNERDRAW | WS_EX_LAYERED, 1, 1,228, 228,
hWnd, (HMENU)CRAPPY, NULL, NULL);
//SetLayeredWindowFromBitmapResource(hButton, ID_THECIRCLE, hInstance);
SetLayeredWindowAttributes(hWnd, 0, 249, LWA_ALPHA);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
SetLayeredWindowFromBitmapResource(hButton, ID_THECIRCLE);
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
//
// FUNCTION: RegisterClass1()
//
// PURPOSE: Registers the class
//
// COMMENTS:
//
//
//
//
void RegisterClass1(HINSTANCE hInstance) {
WNDCLASSEXA wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
//wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hbrBackground = CreateSolidBrush(RGB(255, 0, 0));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;
wc.lpszClassName = g_szClassName;
wc.lpszMenuName = "MENU";
wc.style = CS_HREDRAW | CS_VREDRAW;
if (!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
}
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
Starting from Window 8, WS_EX_LAYERED can be used for child controls.
Method: A manifest file is required to specify at least Window 8 compatibility (sub-layering is only supported from Window 8).
Refer: Targeting your application for Windows
Code Sample: (error check has been removed)
// Test_CustomButton.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "Test_CustomButton.h"
#include <commctrl.h>
#include <system_error>
#pragma comment (lib,"Comctl32.lib")
#define MAX_LOADSTRING 100
#define IDC_OWNERDRAWBUTTON 101
#define CRAPPY 567
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK OwnerDrawButtonProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
void SetLayeredWindowFromBitmapResource(
HWND hwnd, UINT bitmapResourceId, HINSTANCE hInstance = nullptr)
{
DWORD exStyle = ::GetWindowLong(hwnd, GWL_EXSTYLE);
SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED);
struct Resources {
HBITMAP hImage = nullptr;
HGDIOBJ hOldImage = nullptr;
HDC hMemDC = nullptr;
~Resources()
{
if (hMemDC)
{
if (hOldImage)
::SelectObject(hMemDC, hOldImage);
::DeleteDC(hMemDC);
}
if (hImage)
::DeleteObject(hImage);
}
} res;
if (!hInstance)
hInstance = ::GetModuleHandle(nullptr);
res.hImage = reinterpret_cast<HBITMAP>(::LoadImage(
hInstance, MAKEINTRESOURCE(bitmapResourceId), IMAGE_BITMAP,
0, 0, LR_CREATEDIBSECTION));
BITMAP imgInfo{ 0 };
GetObject(res.hImage, sizeof(imgInfo), &imgInfo);
res.hMemDC = ::CreateCompatibleDC(nullptr);
res.hOldImage = ::SelectObject(res.hMemDC, res.hImage);
// Assign the image to the child window, making it transparent.
SIZE size{ imgInfo.bmWidth, imgInfo.bmHeight };
POINT ptSrc{ 0, 0 };
BLENDFUNCTION blend{ AC_SRC_OVER, 0, 200, AC_SRC_ALPHA };
UpdateLayeredWindow(hwnd, nullptr, nullptr, &size, res.hMemDC, &ptSrc,
0, &blend, ULW_ALPHA);
// Destructor of res object will cleanup resources here!
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_TESTCUSTOMBUTTON, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTCUSTOMBUTTON));
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TESTCUSTOMBUTTON));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_TESTCUSTOMBUTTON);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
HWND hButton = CreateWindowEx(0, L"button", NULL, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, 150, 50, 80, 80, hWnd, (HMENU)IDC_OWNERDRAWBUTTON, hInst, NULL);
SetWindowSubclass(hButton, &OwnerDrawButtonProc, IDC_OWNERDRAWBUTTON, 0);
}
break;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// Used be test
HPEN hPen = CreatePen(PS_SOLID, 2, RGB(255, 0, 0));
SelectObject(hdc, hPen);
MoveToEx(hdc, 150, 150, NULL);
LineTo(hdc, 200, 60);
LineTo(hdc, 250, 150);
LineTo(hdc, 150, 150);
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
LRESULT CALLBACK OwnerDrawButtonProc(HWND hWnd, UINT uMsg, WPARAM wParam,
LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
switch (uMsg)
{
case WM_PAINT:
{
RECT rc;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
SetLayeredWindowFromBitmapResource(hWnd, IDB_BITMAP1);
EndPaint(hWnd, &ps);
return 0;
}
case WM_NCDESTROY:
RemoveWindowSubclass(hWnd, &OwnerDrawButtonProc, 1);
break;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
Debug:
Note:
When I tested, I found that the following conditions need to be met:
The image to load must be a 32 bpp, top-down bitmap with
premultiplied alpha channel.
Here is my 32 bpp image for your test.
As I said at the beginning, you need to add a manifest file, you can
create a .manifest file yourself. Then add it in the compiler.
You only need to add the WS_EX_LAYERED style to the child control,
because your requirement is to make the buttons transparent.
In my case the code that was provided didn't work because it was throwing an exception and I didn't add the manifest file properly. I would like to note some things:
Bitmap Images made with gimp do not work; use what was suggested in the thread that I linked in my question and that would be PixelFormer. In Pixel Former go "file", then "Import" and choose your file(in my case it was transparent png of a circle). Next go to "export" and choose bitmap bmp (windows bitmap it will say). Once you do that, already A8:R8:G8:B8 (32bpp) will be selected and you have to next check the last two boxes "Premultiplied Alpha" and "Top-down row order". What has to be said is that image does indeed have an alpha channel and it's transparent. Don't be fooled in opening up in paint and you see a black background and you think the transparency isn't there—— it's there the transparency works... If you open it up it in photoshop (i think) or a sophisiticated image editing program you will see a transparent background in your image.
manifest.xml
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<!-- Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
<!-- Windows Vista -->
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
</application>
</compatibility>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
Copy the above and save it as manifest.xml
The other thing that I would like to note is adding a manifest entry file: in my case I had to add it to C:\Users\Rubel\source\repos\CustomButton2\CustomButton2 so whoever is looking at this in the future, replace that with your directory of your project;for example, C:\Users\blah\source\repos\blah\blah (the blahs with the name of your stuff). Paste your manifest file there (in the directory).
You then have to add it to visual studio. You do this by right clicking in your project in the solution explorer (in my case it was CustomButton2 ) and go to "Manifest Tool" in "Input and Output". In here type in "Additional Manifest Files" the path of your manifest file (in my case it was manifest.xml but if you were following along, then this should be the case as well for your path) and click ok.
That is it, if you used the code ( Strive Sun - MSFT ) that was given it should work.
Here is my final code if anyone was interested:
// CustomButton2.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "CustomButton2.h"
#include <commctrl.h>
#include <gdiplus.h>
#include <system_error>
#define MAX_LOADSTRING 100
#define CRAPPY 567
#define IDC_OWNERDRAWBUTTON 101
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' " "version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
const char g_szClassName[] = "MyClassName";
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
void RegisterClass1(HINSTANCE);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK OwnerDrawButtonProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
void SetLayeredWindowFromBitmapResource(
HWND hwnd, UINT bitmapResourceId, HINSTANCE hInstance = nullptr)
{
DWORD exStyle = ::GetWindowLong(hwnd, GWL_EXSTYLE);
SetWindowLong(hwnd, GWL_EXSTYLE, exStyle | WS_EX_LAYERED);
struct Resources {
HBITMAP hImage = nullptr;
HGDIOBJ hOldImage = nullptr;
HDC hMemDC = nullptr;
~Resources()
{
if (hMemDC)
{
if (hOldImage)
::SelectObject(hMemDC, hOldImage);
::DeleteDC(hMemDC);
}
if (hImage)
::DeleteObject(hImage);
}
} res;
if (!hInstance)
hInstance = ::GetModuleHandle(nullptr);
res.hImage = reinterpret_cast<HBITMAP>(::LoadImage(
hInstance, MAKEINTRESOURCE(bitmapResourceId), IMAGE_BITMAP,
0, 0, LR_CREATEDIBSECTION));
BITMAP imgInfo{ 0 };
GetObject(res.hImage, sizeof(imgInfo), &imgInfo);
res.hMemDC = ::CreateCompatibleDC(nullptr);
res.hOldImage = ::SelectObject(res.hMemDC, res.hImage);
// Assign the image to the child window, making it transparent.
SIZE size{ imgInfo.bmWidth, imgInfo.bmHeight };
POINT ptSrc{ 0, 0 };
BLENDFUNCTION blend{ AC_SRC_OVER, 0, 200, AC_SRC_ALPHA };
UpdateLayeredWindow(hwnd, nullptr, nullptr, &size, res.hMemDC, &ptSrc,
0, &blend, ULW_ALPHA);
// Destructor of res object will cleanup resources here!
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
RegisterClass1(hInstance);
HWND hWnd = CreateWindowExA(WS_EX_LAYERED, g_szClassName, "Scenes", WS_OVERLAPPEDWINDOW | WS_EX_LAYERED, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
hInstance, NULL);
HWND hButton = CreateWindow(TEXT("BUTTON"), TEXT("START EDITING!"), WS_CHILD | WS_VISIBLE | BS_OWNERDRAW | WS_EX_LAYERED, 1, 1,228, 228,
hWnd, (HMENU)CRAPPY, NULL, NULL);
SetWindowSubclass(hButton, &OwnerDrawButtonProc, IDC_OWNERDRAWBUTTON, 0);
//SetLayeredWindowFromBitmapResource(hButton, ID_THECIRCLE, hInstance);
SetLayeredWindowAttributes(hWnd, 0, 249, LWA_ALPHA);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
//SetLayeredWindowFromBitmapResource(hButton, ID_THECIRCLE);
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
//
// FUNCTION: RegisterClass1()
//
// PURPOSE: Registers the class
//
// COMMENTS:
//
//
//
//
void RegisterClass1(HINSTANCE hInstance) {
WNDCLASSEXA wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
//wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hbrBackground = CreateSolidBrush(RGB(255, 0, 0));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wc.hInstance = hInstance;
wc.lpfnWndProc = WndProc;
wc.lpszClassName = g_szClassName;
wc.lpszMenuName = "MENU";
wc.style = CS_HREDRAW | CS_VREDRAW;
if (!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
}
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
LRESULT CALLBACK OwnerDrawButtonProc(HWND hWnd, UINT uMsg, WPARAM wParam,
LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
switch (uMsg)
{
case WM_PAINT:
{
RECT rc;
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
SetLayeredWindowFromBitmapResource(hWnd, ID_THECIRCLE);
EndPaint(hWnd, &ps);
return 0;
}
case WM_NCDESTROY:
RemoveWindowSubclass(hWnd, &OwnerDrawButtonProc, 1);
break;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
Application running :
I know this was verbose but I wanted it to be easy for whoever is encountering this so that they know how to do it.
I am able to create a window with a Tile. How can I add now new text line inside the Window ?
All what I succeed to did was only to change the title of the window which is not what I want . I want to add some text line in the window box.
SendMessage function was not working for me.
Please if somebody has some tip for this to tell me !
#include <windows.h>
const char g_szClassName[] = "myWindowClass";
//The Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
// Registering the Window Class
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
g_szClassName,
"Title of window",
WS_OVERLAPPEDWINDOW,
1390, 540, 240, 120,
NULL, NULL, hInstance, NULL);
if(hwnd == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// The Message Loop
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
To draw text in the client area, your wndProc would normally use something like DrawText or TextOut. You typically do that in response to WM_PAINT.
To be able to respond to an external message, you'd typically send a message containing the text. The window would receive that, store (a copy of) the text it received, and (usually) invalidate the window's rectangle. Since the window is now invalidated, the next chance it gets, Windows will send your window a WM_PAINT message (and then you'll draw out the text).
Handling the WM_PAINT message and drawing the text directly on the window's HDC is one option.
Another option is to create a child STATIC control in your window, and then you can assign the desired text to that child using SetWindowText() or the WM_SETTEXT message. No manual drawing needed.
In the end I figure out how to finish this:
win32 app picture
#ifndef UNICODE
#define UNICODE
#endif
using namespace std;
#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
int X_Coordinate = 215;
int Y_Coordinate = 415;
int Width = 700;
int Height = 500;
char Text[] = {"abc123"};
char Window_Title[] = "My title";
char Window_Image[] = "D:\\bitmap1.bmp";
const char* csWindow_Title = Window_Title;
const char* csWindow_Image = Window_Image;
HBITMAP bitmap; // Creates bitmap object based on a handle to a Windows Windows Graphics Device Interface (GDI) bitmap and a handle to a GDI palette.
// Utilities
bool ConvertConstChartoLPWSTR (const char* as , wchar_t* wString )
{
memset(wString,0,sizeof(wString));
MultiByteToWideChar(CP_ACP, 0, as, -1, wString, 4096);
return wString;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = { };
//Registering the Window Class
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
wc.hbrBackground = CreateSolidBrush(RGB(255, 255, 255)); // set window background color ( RGB ) - white
RegisterClass(&wc); // register the window class with the operating system
wchar_t* wWindow_Title=new wchar_t[4096];
memset(wWindow_Title,0,sizeof(wWindow_Title)); // init variable
ConvertConstChartoLPWSTR(csWindow_Title,wWindow_Title); // convert
// Create the window.
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
wWindow_Title, // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
X_Coordinate, Y_Coordinate, Width, Height,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
// Run the message loop.
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// ----------------------------- START -> SWITCH case -----------------------------------------------------
switch (uMsg)
{
// ----------------------------- START -> case WM_DESTROY -------------------------------------------------
case WM_DESTROY:
PostQuitMessage(0);
return 0;
// ----------------------------- END -> case WM_DESTROY ---------------------------------------------------
// ----------------------------- START -> case WM_PAINT ---------------------------------------------------
case WM_PAINT:
{
wchar_t* wWindow_Image=new wchar_t[4096];
memset(wWindow_Image,0,sizeof(wWindow_Image));
ConvertConstChartoLPWSTR(csWindow_Image,wWindow_Image); // convert
bitmap=(HBITMAP)LoadImage(NULL, // A handle to the module that contains the image to be loaded. To load a stand-alone resource (icon, cursor, or bitmap file)—for example, c:\myimage.bmp — set this parameter to NULL
wWindow_Image, // The image to be loaded.
IMAGE_BITMAP, // The type of image to be loaded.
690, // The width, in pixels, of the icon or cursor.
540, // he height, in pixels, of the icon or cursor.
LR_LOADFROMFILE); //Loads the stand-alone image from the file specified by lpszName (icon, cursor, or bitmap file).
PAINTSTRUCT ps; // declare structure with information for an application
HDC hdc = BeginPaint(hwnd, &ps); // prepare the specified window for painting
int index = sizeof(Text);
HDC hMemDC=CreateCompatibleDC(hdc); // create a compatible DC ( hMemDC ) o be the same like another one ( hdc )
::SelectObject(hMemDC,bitmap); // Selects an object into the specified device context (DC). The new object replaces the previous object of the same type.
long retval=SetTextAlign(hdc,TA_TOP); // alignment of written area
const char* theval;
int u = 5;
for(int b = 0; b < sizeof(Text); b++)
{
string sym(1, Text[b]); // convert char to const char*
theval = sym.c_str();
cout<<b<<theval;
wchar_t wtext[sizeof(Text)];
memset(wtext,0,sizeof(wtext));
ConvertConstChartoLPWSTR(theval,wtext); // convert
// Here application is laid out.
TextOut (hdc, 5, u, wtext, sizeof(Text));
u = u + 15;
}
index = index + u; // claculate the size of written area
BitBlt( hdc, // handler
0, // The x-coordinate, in logical units, of the upper-left corner of the destination rectangle.
index, // The y-coordinate, in logical units, of the upper-left corner of the destination rectangle.
700, // The width, in logical units, of the source and destination rectangles.
980, // The height, in logical units, of the source and the destination rectangles.
hMemDC, // handler for source ( image ).
0, // The x-coordinate, in logical units, of the upper-left corner of the source rectangle.
0, // The y-coordinate, in logical units, of the upper-left corner of the source rectangle.
SRCCOPY ); // A raster-operation code. These codes define how the color data for the source rectangle is to be combined with the color data for the destination rectangle to achieve the final color.
// SRCCOPY - Copies the source rectangle directly to the destination rectangle.
EndPaint(hwnd, &ps); // function marks the end of painting in the specified window
}
return 0;
// ----------------------------- END -> case WM_PAINT ---------------------------------------------------
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
// ----------------------------- END -> SWITCH case -----------------------------------------------------
} // END -> LRESULT CALLBACK WindowProc
I have been driving myself trying to do something that to me seems like it should be relatively straight forward,
I am trying to take a screenshot of specific window (With PrintWindow)
And Display the screenshot over new window (using CreateWindowEx and UpdateLayeredWindow)
The Logic :
TakeNotepadScreenShot->DrawOverWindow->DisplayWindow
something like :
1. Take Notepad Screenshot:
HBITMAP hBmp = PrintWindow(FindWindow("notepad")); //Not Entire Screen, Only notepad
2. Create Window (As Canvas):
HWND hWnd = CreateWindowEx(WS_EX_LAYERED, "WindowClassName", 0, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
3. Draw Notepad Image:
Draw_HBitmap_OverWindow(hBmp,hWnd);
//Using UpdateLayeredWindow
4. Show Window / Display Notepad Screenshot
ShowWindow(hWnd, SW_SHOW);
See: How to get screenshot of a window as bitmap object in C++? << Thats How To Take Notepad ScreenShot
But how to display the image? (C++/Console Application/Empty Project)
You'd better create a Windows Desktop Application.
I have add a "Print" Menu, Then Add
PrintWindow(FindWindow(L"Notepad", L"xxx.txt - Notepad"), GetDC(hWnd), 0);
.cpp:
// WindowsProject9.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "WindowsProject9.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_WINDOWSPROJECT9, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WINDOWSPROJECT9));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WINDOWSPROJECT9));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_WINDOWSPROJECT9);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
case ID_HELP_PRINT:
PrintWindow(FindWindow(L"Notepad", L"xxx.txt - Notepad"), GetDC(hWnd), 0);
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
EDIT:
I have uploaded the project on my onedrive, this is the link.
win32 windows application and want to capture full screen and remove the border of window displayed any one tell me how can i do so if this window capture the mouse keyboard controls then it will be ideal?
// MonitorScreen.cpp : Defines the entry point for the application. //
#include "stdafx.h"
#include "MonitorScreen.h
#define MAX_LOADSTRING 100
// Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here. MSG msg; HACCEL hAccelTable;
// Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_MONITORSCREEN, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance);
// Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; }
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MONITORSCREEN));
// Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
return (int) msg.wParam; }
// // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage are only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex;
int s =sizeof(WNDCLASSEX); wcex.cbSize =sizeof(WNDCLASSEX);
wcex.style = DESKTOP_HOOKCONTROL ;//CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = NULL;//hInstance; wcex.hIcon = NULL;//LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MONITORSCREEN)); wcex.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(9); wcex.lpszMenuName = NULL;//MAKEINTRESOURCE(IDC_MONITORSCREEN); wcex.lpszClassName = szWindowClass; wcex.hIconSm = NULL;//LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex); }
// // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd) {
return FALSE; }
ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd);
return TRUE; }
// // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc;
switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent
= HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
// Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE;
case WM_COMMAND: if (LOWORD(wParam)
== IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
I'm going to assume you don't actually want to capture the screen, your question cannot make sense. I'm guessing you simply want to make your window maximized to occupy the full screen. Put the template generated code back the way it was, simply change the ShowWindow call:
ShowWindow(hWnd, SW_MAXIMIZE);
Found this on google: Difficulties with Screen Capture, C/C++...
Try to understand the code and adjust it to you needs.
void CaptureScreen(LPCTSTR lpszFilePathName)
{
BITMAPFILEHEADER bmfHeader;
BITMAPINFO *pbminfo;
HBITMAP hBMP;
CFile oFile;
CDC *pDC = GetWindowDC();
INT nSizeImage = 1024 * 768 * 3;
CHAR *pBuff = new CHAR[sizeof(BITMAPINFOHEADER) + nSizeImage];
pbminfo = (BITMAPINFO *)pBuff;
hBMP = (HBITMAP)pDC->GetCurrentBitmap()->m_hObject;
ZeroMemory(pbminfo, sizeof(BITMAPINFO));
pbminfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
GetDIBits(pDC->m_hDC,
hBMP,
0,
1,
NULL,
pbminfo,
DIB_RGB_COLORS);
GetDIBits(pDC->m_hDC,
hBMP,
0,
pbminfo->bmiHeader.biHeight,
pBuff + sizeof(BITMAPINFOHEADER),
pbminfo,
DIB_RGB_COLORS);
ReleaseDC(pDC);
bmfHeader.bfType = 0x4d42; /*"BM"*/
bmfHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + nSizeImage;
bmfHeader.bfReserved1 = 0;
bmfHeader.bfReserved2 = 0;
bmfHeader.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
oFile.Open(lpszFilePathName, CFile::modeWrite | CFile::modeCreate);
oFile.Write(&bmfHeader, sizeof(BITMAPFILEHEADER));
oFile.Write(pBuff, sizeof(BITMAPINFOHEADER) + pbminfo->bmiHeader.biSizeImage);
delete []pBuff;
oFile.Close();
}
I think you want to use OpenGL or DirectX and invoke full-screen mode for your application. There will of course be a few keystrokes you can't intercept, such as the Secure Attention Sequence (usually CTRL+ALT+DEL) but most interaction with the computer will be directed to your program.
first to get the full screen you should type this in:
ShowWindow(hWnd, SW_SHOWMAXIMIZED)
Second to remove the border or witch is called thick frame in the window styles you should type in your CreateWindow function(the place where you put your styles (WS_)):
CreateWindow(your class,
window name,
WS_POPUP | WS_BORDER,
The rest of your params for the create window func.);
Ps:WS_BORDER IS JUST A 1 PX BLACK BORDER so you can know where is the window if it was not minimized and on top of a window woth the same bg color AND YOU CAN REMOVE IT WHENEVER YOU WANT
Also you wont be able to minimize,maximize,close the window with the built in buttons because they wont be there so if you want to close the app just make a button that sends a PostQuitMessage when pressed.
good luck