Using the following code to update my application with an external exe file, I get paint corruption (not update or refresing) to window under -which is the main app and the caller- when I move this window. It seems that under Windows 7 works fine but under window XP I have this problem.
void CMainFrame::OnBtnUpdateApp() {
SHELLEXECUTEINFO lpExecInfo;
DWORD dwExitCode;
HINSTANCE hProcess = 0;
BOOL bResult;
ZeroMemory(&lpExecInfo,sizeof(lpExecInfo));
lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
lpExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
lpExecInfo.hwnd = GetSafeHwnd();
lpExecInfo.lpVerb = _T("open");
lpExecInfo.lpFile = _T("Update.exe");
lpExecInfo.lpParameters = _T("");
lpExecInfo.lpDirectory = _T("");
lpExecInfo.nShow = SW_SHOWNORMAL;
lpExecInfo.hInstApp = NULL;
lpExecInfo.hProcess = hProcess;
bResult = ShellExecuteEx(&lpExecInfo);
if(bResult) {
WaitForSingleObject( lpExecInfo.hProcess, INFINITE );
if (!GetExitCodeProcess(lpExecInfo.hProcess, &dwExitCode)) {
//failed to terminate normally
}
CloseHandle(lpExecInfo.hProcess);
} else {
//failed to execute the exe file
}
}
What seems to be wrong here ?
You're not processing any window messages during WaitForSingleObject.
Re the difference between Windows XP and Windows 7, the Desktop Window Manager technology in Windows 7 was introduced with Windows Vista, and was not available in Windows XP. Essentially it provides a layer of indirection between each app's painting actions and the result on screen.
A reasonable way to launch and wait for a program is to disable the main window the window's user interface parts and then poll the program's exit status in a peek-message loop.
Example, except that it uses CreateProcess (I coded it up without remembering to check the question, and now it's pretty late in the evening, but better with imperfect help than no help, I think):
#include <windows.h> // UNICODE, NOMINMAX, STRICT, WIN32_LEAN_AND_MEAN
#include <windowsx.h> // Message cracker macros, e.g. HANDLE_WM_DESTROY
#include <assert.h>
#include <stdexcept>
#include <string>
using namespace std;
auto hopefully( bool const condition ) -> bool { return condition; }
auto fail( string const& s ) -> bool { throw runtime_error( s ); }
struct Window_class_id
{
ATOM value;
auto as_pointer() const -> wchar_t const* { return MAKEINTATOM( value ); }
};
auto get_message( MSG& m )
-> bool
{
int const result = GetMessage( &m, 0, 0, 0 );
hopefully( result != -1 )
|| fail( "GetMessage failed" );
return !!result;
}
auto peek_message( MSG& m )
-> bool
{
int const result = PeekMessage( &m, 0, 0, 0, TRUE );
hopefully( result != -1 )
|| fail( "PeekMessage failed" );
return !!result;
}
void empty_message_queue()
{
MSG m;
while( peek_message( m ) )
{
TranslateMessage( &m );
DispatchMessage( &m );
}
}
auto dispatch_messages()
-> DWORD // Exit code from WM_QUIT
{
MSG msg;
while( get_message( msg ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
assert( msg.message == WM_QUIT );
return msg.wParam;
}
auto run( wchar_t const command[] )
-> HANDLE
{
wstring commandline = command;
hopefully( commandline.length() > 0 )
|| fail( "run: Empty command line" );
STARTUPINFO in_params = { sizeof( STARTUPINFO ) };
PROCESS_INFORMATION out_params = {};
bool const success = !!CreateProcess(
nullptr, // app name
&commandline[0],
nullptr, // process attributes
nullptr, // thread attributes
false, // inherit handles
0, // creation flags
nullptr, // environment block
nullptr, // current directory
&in_params, // startup info
&out_params // process info
);
hopefully( success )
|| fail( "run: CreateProcess failed" );
CloseHandle( out_params.hThread );
return out_params.hProcess;
}
namespace main_window
{
namespace command_id {
int const run_fun = 101;
} // namespace command
namespace run_button {
int const id = command_id::run_fun;
} // namespace run_button
namespace command {
void run_fun( HWND const window )
{
EnableWindow( GetDlgItem( window, run_button::id ), false );
UpdateWindow( window );
empty_message_queue();
HANDLE const process = run( L"notepad" );
for( ;; )
{
DWORD const result = WaitForSingleObject( process, 100 );
if( result == WAIT_OBJECT_0 )
{
break;
}
empty_message_queue();
}
CloseHandle( process );
EnableWindow( GetDlgItem( window, run_button::id ), true );
}
} // namespace command
void on_command( HWND const window, int const id )
{
switch( id )
{
case command_id::run_fun: return command::run_fun( window );
}
}
void on_wm_command(
HWND const window,
int const control_or_command_id,
HWND const control,
UINT const notification_code
)
{
if( control == 0 )
{
int const command_id = control_or_command_id;
on_command( window, command_id );
}
else
{
int const control_id = control_or_command_id;
switch( control_id )
{
case run_button::id:
if( notification_code == BN_CLICKED )
{
int const command_id = control_id;
on_command( window, command_id );
}
}
}
}
auto on_wm_create( HWND const window, CREATESTRUCT const* const p_params )
-> bool // `true` if creation succeeded.
{
(void) p_params;
HWND const button_handle = CreateWindow(
L"button", L"Run the fun", WS_CHILD | WS_VISIBLE,
10, 10, 120, 26,
window, // parent
reinterpret_cast<HMENU>( run_button::id ),
GetModuleHandle( 0 ),
0 // lpParam
);
return (button_handle != 0);
}
void on_wm_destroy( HWND const window )
{
(void) window;
PostQuitMessage( 0 );
}
auto CALLBACK message_handler(
HWND const window,
UINT const message_id,
WPARAM const word_param,
LPARAM const long_param
)
-> LRESULT
{
switch( message_id )
{
case WM_COMMAND: return HANDLE_WM_COMMAND(
window, word_param, long_param, on_wm_command );
case WM_CREATE: return HANDLE_WM_CREATE(
window, word_param, long_param, on_wm_create );
case WM_DESTROY: return HANDLE_WM_DESTROY(
window, word_param, long_param, on_wm_destroy );
}
return DefWindowProc( window, message_id, word_param, long_param );
}
} // namespace main_window
auto register_window_class()
-> Window_class_id
{
WNDCLASS params = {};
params.style = CS_DBLCLKS;
params.lpfnWndProc = main_window::message_handler;
params.hInstance = GetModuleHandle( 0 );
params.hIcon = LoadIcon( 0, IDI_APPLICATION );
params.hCursor = LoadCursor( 0, IDC_ARROW );
params.hbrBackground = reinterpret_cast<HBRUSH>( COLOR_WINDOW );
params.lpszClassName = L"MainWindow_class";
ATOM const id = RegisterClass( ¶ms );
hopefully( id != 0 )
|| fail( "RegisterClass failed" );
return {id};
}
auto create_window( Window_class_id const& class_id )
-> HWND
{
HWND const handle = CreateWindow(
class_id.as_pointer(),
L"Fun run",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 380, 221, // x, y, w, h
0, 0, // parent, menu
GetModuleHandle( 0 ),
0 // lpParam
);
hopefully( handle != 0 )
|| fail( "CreateWindow failed" );
return handle;
}
void cpp_main()
{
Window_class_id const class_id = register_window_class();
HWND const window = create_window( class_id );
ShowWindow( window, SW_SHOWDEFAULT );
int const exit_code = static_cast<int>( dispatch_messages() );
hopefully( exit_code == 0 )
|| fail( "WM_QUIT indicated failure" );
}
auto main() -> int
{
try{ cpp_main(); } catch( ... ) { return E_FAIL; }
return 0;
}
Related
In my C++ application, a CHTMLView is used to load some HTML into a web page. It works by writing the HTML to a temporary file, and then calling Navigate2() on the CHTMLView to navigate to the file location.
What we are finding happens is that the navigation occurs, the file is written, the completely correct contents of the page appears, but then it quickly disappears and becomes blank. But it's a visual thing; right-clicking and saying "View Source" shows the correct source, and hovering over elements on the page that react to hovering make them appear again (but everything else stays white). Resizing the window or scrolling is the only way to make everything appear.
I have tried navigating first to about:blank and then triggering a navigation to the correct place with a OnDocumentComplete() event. I have even tried navigating first to blank dummy page and then going from there. Nothing changes.
Any advice?!
The derived class is ScriptViewer.
ScriptViewer.h
class CScriptViewer : public CHtmlView
{
protected:
CScriptViewer(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CScriptViewer)
// html Data
public:
//{{AFX_DATA(CScriptViewer)
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Attributes
public:
CAMAgentDesktopDoc* m_pDoc;
CScriptDlg* m_pDlg;
CString strScriptLocation;
BOOL m_bInitialLoad;
// Operations
public:
void GetAllValues( map<CString,CString>& mValues );
void GetValuesIn( IHTMLDocument2* pHTMLDoc, map<CString,CString>& mValues );
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CScriptViewer)
public:
virtual void OnInitialUpdate();
virtual void OnBeforeNavigate2(LPCTSTR lpszURL, DWORD nFlags, LPCTSTR lpszTargetFrameName, CByteArray& baPostedData, LPCTSTR lpszHeaders, BOOL* pbCancel);
virtual void OnDocumentComplete(LPCTSTR lpszURL);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~CScriptViewer();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
CAMTrace m_trace;
// Generated message map functions
//{{AFX_MSG(CScriptViewer)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
ScriptViewer.cpp
CScriptViewer::CScriptViewer()
{
//{{AFX_DATA_INIT(CScriptViewer)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
m_trace.SetEXEName( _T("CScriptViewer") );
m_trace.Trace( _T("constructor"), FALSE, 0 );
strScriptLocation = _T("");
m_bInitialLoad = FALSE;
m_pDoc = NULL;
m_pDlg = NULL;
}
CScriptViewer::~CScriptViewer()
{
/*
map<CString,CString> mValues;
GetAllValues( mValues );
m_pDlg->UpdateUserEnteredValues( mValues );
*/
m_trace.Trace( _T("destructor"), FALSE, 0 );
}
void CScriptViewer::DoDataExchange(CDataExchange* pDX)
{
CHtmlView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CScriptViewer)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CScriptViewer, CHtmlView)
//{{AFX_MSG_MAP(CScriptViewer)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CScriptViewer diagnostics
#ifdef _DEBUG
void CScriptViewer::AssertValid() const
{
CHtmlView::AssertValid();
}
void CScriptViewer::Dump(CDumpContext& dc) const
{
CHtmlView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CScriptViewer message handlers
void CScriptViewer::OnInitialUpdate()
{
try
{
m_trace.Trace( _T("OnInitialUpdate") );
ASSERT( m_pDoc );
ASSERT( m_pDlg );
}
catch(...)
{
}
}
void CScriptViewer::OnBeforeNavigate2(LPCTSTR lpszURL, DWORD nFlags, LPCTSTR lpszTargetFrameName, CByteArray& baPostedData, LPCTSTR lpszHeaders, BOOL* pbCancel)
{
try
{
map<CString,CString> mValues;
GetAllValues( mValues );
ASSERT( m_pDlg );
// GJS
if (!m_pDlg) return;
m_pDlg->UpdateUserEnteredValues( mValues );
CString strURL = lpszURL;
int nPosClose = strURL.Find( URL_INSTRUCTION_TO_ADAPTIVE_DESKTOP );
if ( nPosClose > 0 )
{
*pbCancel = TRUE;
CHtmlView::OnBeforeNavigate2(lpszURL, nFlags, lpszTargetFrameName, baPostedData, lpszHeaders, pbCancel);
m_pDlg->OnScriptInstructionToDesktop( strURL.Mid( nPosClose + _tcslen(URL_INSTRUCTION_TO_ADAPTIVE_DESKTOP) ), mValues );
}
else
{
CHtmlView::OnBeforeNavigate2(lpszURL, nFlags, lpszTargetFrameName, baPostedData, lpszHeaders, pbCancel);
}
}
catch(...)
{
}
}
void CScriptViewer::OnDocumentComplete(LPCTSTR lpszURL) {
if (!m_bInitialLoad) {
//Navigate2(strScriptLocation);
//m_bInitialLoad = TRUE;
}
}
///////////////////////////////////////////////////////////////////////////////////
// accessing data values from the HTML pages, after the user has fiddled with them
void CScriptViewer::GetValuesIn( IHTMLDocument2* pHTMLDoc, map<CString,CString>& mValues )
{
try
{
if ( pHTMLDoc != NULL )
{
BSTR bsURL;
VERIFY( SUCCEEDED( pHTMLDoc->get_URL( &bsURL ) ) );
// TRACE( _T("GetValuesIn(%s)\r\n"), CString(bsURL) );
IHTMLFramesCollection2* pFrames = NULL;
if ( SUCCEEDED( pHTMLDoc->get_frames( &pFrames ) ) )
{
long lNumFrames = 0;
VERIFY( SUCCEEDED( pFrames->get_length( &lNumFrames ) ) );
for( long l = 0; l < lNumFrames; l++ )
{
COleVariant v1(l);
VARIANT vDispFrame;
if ( SUCCEEDED( pFrames->item( v1, &vDispFrame ) ) )
{
if ( vDispFrame.vt == VT_DISPATCH )
{
IHTMLWindow2* pWindow = NULL;
VERIFY( SUCCEEDED( (vDispFrame.pdispVal)->QueryInterface( IID_IHTMLWindow2, (LPVOID*)&pWindow ) ) );
ASSERT( pWindow );
IHTMLDocument2* pSubDoc = NULL;
if ( SUCCEEDED( pWindow->get_document( &pSubDoc ) ) )
{
GetValuesIn( pSubDoc, mValues );
pSubDoc->Release();
}
pWindow->Release();
}
}
}
pFrames->Release();
}
IHTMLElementCollection* pElemColl = NULL;
HRESULT hr = pHTMLDoc->get_all(&pElemColl);
if (SUCCEEDED(hr) && pElemColl)
{
long lNumElements = 0;
VERIFY( SUCCEEDED( pElemColl->get_length( &lNumElements ) ) );
for( long l = 0; l < lNumElements; l++ )
{
COleVariant v1(l);
COleVariant vzero((long)0);
LPDISPATCH pDispTemp = NULL;
VERIFY( SUCCEEDED( pElemColl->item( v1, vzero, &pDispTemp ) ) );
ASSERT( pDispTemp != NULL );
IHTMLElement* pel = NULL;
VERIFY( SUCCEEDED( pDispTemp->QueryInterface( IID_IHTMLElement, (LPVOID*)&pel ) ) );
CString str;
BSTR bsid;
pel->get_id( &bsid );
VARIANT vValue;
pel->getAttribute( CString("value").AllocSysString(), 0, &vValue );
CString strID = CString(bsid);
if ( !strID.IsEmpty() )
{
CString strValue = _T("");
if ( vValue.vt == VT_BSTR ) {
strValue = CString(vValue.bstrVal);
} else if ( vValue.vt == VT_I2 || vValue.vt == VT_I4 ) {
strValue.Format( _T("%d"), vValue.intVal );
}
mValues[strID] = strValue;
// str.Format( _T("ID %s, value %s\r\n"),
// strID, strValue );
// strRetval += str;
}
pel->Release();
}
pElemColl->Release();
}
else
ASSERT(FALSE);
}
else
ASSERT(FALSE); // passed null object doc
}
catch(...)
{
}
}
void CScriptViewer::GetAllValues( map<CString,CString>& mValues )
{
try
{
mValues.clear();
LPDISPATCH pDisp = GetHtmlDocument();
if ( pDisp )
{
IHTMLDocument2* p = NULL;
if ( SUCCEEDED( pDisp->QueryInterface( IID_IHTMLDocument2, (LPVOID*)&p ) ) && p != NULL )
{
GetValuesIn( p, mValues );
p->Release();
}
else
ASSERT(FALSE); // unable to QI for IHTMLDocument2?
pDisp->Release();
}
}
catch(...)
{
}
}
Here is the code that handles the navigation:
CString strFilePath = CAMMiscSharedFilePaths::GetFullPathToWindowsTempDir() + _T("\\") + m_call->m_camCampaignSettings.m_scriptView.m_strName+_T("_temp.htm");
HRESULT hr = WriteStringToTextFile( strFilePath, strRedirect ); //intentionally left for html settings, as it stores data in windows temp
if ( SUCCEEDED(hr) ) {
pView->strScriptLocation = strFilePath;
CString str = strFilePath;
pView->Navigate2(str);
}
Here is my derived class of a CHTMLView. I load the HTML directly into the browser. Works for me, maybe you can use it:
#include "stdafx.h"
#include "GMHtmlView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGMHtmlView, CHtmlView)
CGMHtmlView::CGMHtmlView(IHtmlEventNotifier* pHEN)
{
EnableToolTips(FALSE);
m_pBrowser = NULL;
m_pBrowserDispatch = NULL;
m_pHEN = pHEN;
m_strPrefix = "http://";
}
void CGMHtmlView::DoDataExchange(CDataExchange* pDX)
{
CHtmlView::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CGMHtmlView, CHtmlView)
END_MESSAGE_MAP()
BOOL CGMHtmlView::Create(const RECT &rect,CWnd* pParentWnd)
{
BOOL bRet = CHtmlView::Create(NULL,NULL,WS_VISIBLE,rect,pParentWnd,AFX_IDW_PANE_FIRST);
// Pointer auf Browser herausfinden
if(bRet)
{
LPUNKNOWN unknown = GetDlgItem(0)->GetControlUnknown();
HRESULT hr = unknown->QueryInterface(IID_IWebBrowser2,(void **)&m_pBrowser);
if (SUCCEEDED(hr))
hr = unknown->QueryInterface(IID_IDispatch,(void **)&m_pBrowserDispatch);
}
return bRet;
}
void CGMHtmlView::SetPrefix(const CString& prefix)
{
m_strPrefix = prefix;
}
void CGMHtmlView::OnBeforeNavigate2(LPCTSTR lpszURL, DWORD nFlags, LPCTSTR lpszTargetFrameName, CByteArray& baPostedData, LPCTSTR lpszHeaders, BOOL* pbCancel)
{
CString url(lpszURL);
url.MakeLower();
// Sperre: alles andere als die leere Seite
// und unser Inhalt wird gesperrt
if(url == "about:blank")
{
CHtmlView::OnBeforeNavigate2(lpszURL,nFlags,lpszTargetFrameName,baPostedData,lpszHeaders,pbCancel);
return;
}
if(url.Find(m_strPrefix) != 0)
{
*pbCancel = TRUE;
return;
}
// jetzt die Adresse nach aussen weiterleiten
if(m_pHEN)
{
url = url.Right(url.GetLength() - m_strPrefix.GetLength());
m_pHEN->UrlNotify(url);
}
}
void CGMHtmlView::Clear()
{
if(!IsWindow(m_hWnd))
return;
IHTMLDocument2* pDoc = GetDocument();
if(!pDoc)
{
Navigate2("about:blank");
return;
}
pDoc->close();
VARIANT open_name;
VARIANT open_features;
VARIANT open_replace;
IDispatch *open_window = NULL;
::VariantInit(&open_name);
open_name.vt = VT_BSTR;
open_name.bstrVal = ::SysAllocString(L"_self");
::VariantInit(&open_features);
::VariantInit(&open_replace);
HRESULT hr = pDoc->open(::SysAllocString(L"text/html"),open_name,open_features,
open_replace,&open_window);
if (hr == S_OK)
Refresh();
if (open_window != NULL)
open_window->Release();
}
void CGMHtmlView::LoadHTML(const CString& html)
{
if(!IsWindow(m_hWnd))
return;
Clear();
IHTMLDocument2* pDoc = GetDocument();
if(!pDoc)
return;
SAFEARRAY* sa = SafeArrayCreateVector(VT_VARIANT,0,1);
VARIANT* var;
SafeArrayAccessData(sa,(LPVOID*) &var);
var->vt = VT_BSTR;
var->bstrVal = html.AllocSysString();
SafeArrayUnaccessData(sa);
pDoc->write(sa);
pDoc->Release();
}
IHTMLDocument2* CGMHtmlView::GetDocument()
{
IHTMLDocument2* document = NULL;
if (m_pBrowser != NULL)
{
IDispatch *document_dispatch = NULL;
HRESULT hr = m_pBrowser->get_Document(&document_dispatch);
if (SUCCEEDED(hr) && (document_dispatch != NULL))
{
hr = document_dispatch->QueryInterface(IID_IHTMLDocument2,(void **)&document);
document_dispatch->Release();
}
}
return document;
}
void CGMHtmlView::AssertValid() const
{
//CHtmlView::AssertValid();
}
void CGMHtmlView::PostNcDestroy()
{
//CHtmlView::PostNcDestroy();
}
There are some similar topics on SO, but I haven't found all I need.
I have the following C++ Code:
string getConsoleOutput(string command)
{
string data;
File *fp;
char var[512];
fp = _popen(command.c_str(), "r");
while (fgets(var, sizeof(var), fp) != NULL)
{
data += var;
}
_pclose(fp);
return data;
}
The problem is that every time I send a console command to this function, the command line pops up.
I want to send a command to the Console and get the output without seeing a Console Window.
EDIT:
I tried out libexec, but it is too complex for my needs
I also read about WinExec and CreateProcess, but I haven't found a way to get the output
If it is okay with a little flash on the screen, then just include a command to hide the window. Since AFAIK Windows doesn't itself offer such a command (although it may be lurking in the deeps of Powershell), you will have to create it. But that's trivial:
#define UNICODE
#define NOMINMAX
#include <windows.h>
auto main() -> int
{
ShowWindow( GetConsoleWindow(), SW_HIDE );
}
I've tested that the _popen functionality works OK with hidden window.
And contrary to the documentation, it apparently also works OK for a GUI subsystem application, although I didn't test more than a dir command.
If the flash is unacceptable, then you can use CreateProcess to fire up a hidden command intepreter window, and low level Windows pipes to catch the output.
Sorry, I first wrote a suggestion here about COMSPEC and a GUI subsystem faux command interpreter, which works as far as I tested it, but it would just involve the above again for catching the command interpreter output. I.e. using _popen in the main program would then just be added complication and inefficiency. Better to do it directly at the API level.
An example.
Disclaimer: I am pretty sure I'm doing something wrong here, because when the command process terminates the pipe should generate EOF, no bytes read. Instead the ReadFile call would then just hang, so I had to add a very ugly wait-for-data-or-process-termination loop before calling ReadFile. On the other hand, I remember that Windows had some bugs related to pipes and EOF. So pretty sure is not 100% sure, but I haven't had time to check out MS example.
#define NOMINMAX
#define STRICT
#define UNICODE
#include <windows.h>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;
auto hopefully( const bool condition ) -> bool { return condition; }
auto fail( const string& message ) -> bool { throw runtime_error( message ); }
struct Non_copyable
{
Non_copyable& operator=( const Non_copyable& ) = delete;
Non_copyable( const Non_copyable& ) = delete;
Non_copyable() {}
Non_copyable( Non_copyable&& ) {}
};
struct Process
: Non_copyable
{
HANDLE handle;
~Process() { CloseHandle( handle ); }
Process( const HANDLE h = 0 ): handle( h ) {}
Process( Process&& other ): handle( other.handle ) { other.handle = 0; }
};
auto environment_var( const wstring& name )
-> wstring
{
const DWORD buffer_size = GetEnvironmentVariable( name.c_str(), nullptr, 0 );
hopefully( buffer_size > 0 )
|| fail( "environment_var: GetEnvironmentVariable failed 1st call." );
wstring result( buffer_size + 1, L'#' );
const DWORD n_characters = GetEnvironmentVariable(
name.c_str(), &result[0], result.size()
);
hopefully( n_characters > 0 )
|| fail( "environment_var: GetEnvironmentVariable failed 2nd call." );
result.resize( n_characters ); // Just for good measure.
return result;
}
auto exit_code_of( const HANDLE process )
-> int
{
DWORD code = E_FAIL;
GetExitCodeProcess( process, &code );
return code;
}
auto has_terminated( const HANDLE process )
-> bool
{ return exit_code_of( process ) != STILL_ACTIVE; }
auto start_command( const wstring& command, const HANDLE output_handle = INVALID_HANDLE_VALUE )
-> Process
{
const wstring com_spec = environment_var( L"COMSPEC" );
wstring command_line = com_spec + L" /c " + command; // Can not be `const`.
STARTUPINFO params = { sizeof( STARTUPINFO ) };
if( output_handle != INVALID_HANDLE_VALUE )
{
const HANDLE nul = CreateFile( L"nul", GENERIC_ALL, 0, nullptr, OPEN_EXISTING, 0, 0 );
params.dwFlags = STARTF_USESTDHANDLES;
params.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
params.hStdOutput = output_handle;
params.hStdError = GetStdHandle( STD_ERROR_HANDLE );
}
PROCESS_INFORMATION info = {};
bool const process_was_created = !!CreateProcess(
nullptr, // LPCTSTR lpApplicationName,
&command_line[0], // LPTSTR lpCommandLine,
nullptr, // LPSECURITY_ATTRIBUTES lpProcessAttributes,
nullptr, // LPSECURITY_ATTRIBUTES lpThreadAttributes,
true, // BOOL bInheritHandles,
CREATE_NO_WINDOW, // DWORD dwCreationFlags,
nullptr, // LPVOID lpEnvironment,
nullptr, // LPCTSTR lpCurrentDirectory,
¶ms, // LPSTARTUPINFO lpStartupInfo,
&info // LPPROCESS_INFORMATION lpProcessInformation
);
if( not process_was_created ) { return 0; }
CloseHandle( info.hThread );
return info.hProcess;
}
auto command_result( const wstring& command )
-> string
{
struct Pipe
{
HANDLE read_handle = 0;
HANDLE write_handle = 0;
~Pipe() { CloseHandle( read_handle ); CloseHandle( write_handle ); }
};
Pipe pipe;
SECURITY_ATTRIBUTES params = { sizeof( SECURITY_ATTRIBUTES ) };
params.bInheritHandle = TRUE;
CreatePipe( &pipe.read_handle, &pipe.write_handle, ¶ms, 0 )
|| fail( "command_result: CreatePipe failed" );
SetHandleInformation( pipe.read_handle, HANDLE_FLAG_INHERIT, 0 ); // Inheritance ungood.
const Process process = { start_command( command, pipe.write_handle ) };
if( process.handle == 0 ) { return ""; }
string result;
for( ;; )
{
// Wait for data to become available or process terminated, to avoid hanging.
for( ;; )
{
DWORD n_bytes_available = 0;
const bool ok = !!PeekNamedPipe(
pipe.read_handle, nullptr, 0, nullptr, &n_bytes_available, nullptr
);
if( ok && n_bytes_available > 0 ) { break; }
if( has_terminated( process.handle ) ) { return result; }
Sleep( 125 );
}
char buffer[4096];
DWORD n_bytes_read = 0;
SetLastError( 0 );
ReadFile( pipe.read_handle, buffer, sizeof( buffer ), &n_bytes_read, nullptr )
|| fail( "command_result: ReadFile failed" );
const auto last_read_error = GetLastError();
if( last_read_error != 0 ) { break; }
if( n_bytes_read == 0 ) { break; }
result.append( buffer, n_bytes_read );
}
return result;
}
auto main() -> int
{
try
{
const string result = command_result( L"dir *" );
const wstring text( result.begin(), result.end() );
MessageBox( 0, text.c_str(), L"Result:", MB_SETFOREGROUND );
return 0;
}
catch( const exception& x )
{
MessageBoxA( 0, x.what(), "Oops, an exception", MB_ICONERROR | MB_SETFOREGROUND );
}
return E_FAIL;
}
I have two classes defined as:
class Control
{
private:
std::vector<int> Info;
public:
Control(..);
virtual ~Control();
LRESULT __stdcall SubClass(HWND Window, UINT Msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
};
class Button: public Control
{
//...
};
Control::Control(..)
{
SetWindowSubclass(..., SubClass, ...); //Need to pass member function as callback..
}
LRESULT __stdcall Control::SubClass(HWND Window, UINT Msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
//Use "Info" data member in here.. thus I cannot have static callback in order to use it.
}
And so I came up with:
class Control
{
private:
std::vector<int> Info;
static LRESULT __stdcall SetCallback(void* ThisPtr) {return static_cast<Control*>(ThisPtr)->SubClass;};
public:
//all the same stuff..
};
Control::Control(..)
{
SetWindowSubclass(..., SetCallback, ...);
}
But the above throws a whole bunch of errors. Is there anyway to either have my static callback access other datamembers OR have my callback non-static?
I do not want to have to do something like the following for every instance created (which I've seen as suggestions all over the internet):
Control F;
F.SetCallback(&F::SubClass, &F); //Externally sets member as callback which I don't want.
I'm trying to keep everything in the constructor or the class itself.
This is probably the most common question when it comes to Win32 API UI programming. See:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff381400(v=vs.85).aspx
Basically the trick is to call SetWindowLongPtr with GWLP_USERDATA as the first parameter and this as the second. Then in the WindowProc callback use GetWindowLongPtr to get it from the HWND.
The following shows how to pass calls to the freestanding message handler function, on to a member function of your C++ object.
It's a lot of code, but normally you would abstract this away in some reusable module, and the most basic stuff is just the little class gui::api_level::window_subclasser_t.
I haven't shown very much error handling, and neither does this code support programmatic destruction of the C++ object via external delete (I think the sane way to do this is to just DestroyWindow the API level window and let that propagate up to self-destruction of the C++ object, but it's many years since last time I did this).
#undef UNICODE
#define UNICODE
#undef NOMINMAX
#define NOMINMAX
#undef STRICT
#define STRICT
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
//#include <windowsx.h>
#include <commctrl.h> // SetWindowSubclass
#include <assert.h> // assert
#include <stdexcept> // std::exception, std::runtime_error
#include <stdlib.h> // EXIT_SUCCESS, EXIT_FAILURE
#include <string> // std::string
#ifndef IS_DELETED
# define IS_DELETED = delete // C++11
#endif
namespace cpp {
using namespace std;
bool hopefully( bool condition ) { return condition; }
bool throw_x( string const& s ) { throw runtime_error( s ); }
} // namespace cpp
namespace winapi {
using cpp::hopefully;
using cpp::throw_x;
bool get( MSG& m )
{
int const code = ::GetMessage( &m, 0, 0, 0 );
hopefully( code >= 0 )
|| throw_x( "winapi::get( MSG ): GetMessage failed" );
return !!code;
}
} // namespace winapi
namespace gui {
using cpp::hopefully;
using cpp::throw_x;
namespace api_level
{
class message_handler_t
{
public:
virtual LRESULT window_proc( MSG const& message ) = 0;
};
LRESULT CALLBACK main_window_subclassproc(
HWND const window,
UINT const message_id,
WPARAM const w_param,
LPARAM const l_param,
UINT_PTR const subclass_id,
DWORD_PTR const data
)
{
(void) subclass_id; struct subclass_id;
auto const p_handler = reinterpret_cast< message_handler_t* >( data );
MSG const message = { window, message_id, w_param, l_param, DWORD(), POINT() };
return p_handler->window_proc( message );
}
class window_subclasser_t
{
private:
enum { subclass_id = 1 };
HWND window_handle_;
window_subclasser_t( window_subclasser_t const& ) IS_DELETED;
window_subclasser_t& operator=( window_subclasser_t const& ) IS_DELETED;
public:
HWND handle() const { return window_handle_; }
LRESULT pass_to_superclass( MSG const& m )
{
return ::DefSubclassProc( m.hwnd, m.message, m.wParam, m.lParam );
}
~window_subclasser_t()
{
::RemoveWindowSubclass(
window_handle_,
&main_window_subclassproc,
subclass_id
)
|| throw_x( "gui::api_level::window_subclass_t::<destroy>(): RemoveWindowSubclass failed" );
}
window_subclasser_t(
HWND const api_window,
message_handler_t* cpp_window
)
: window_handle_( api_window )
{
assert( cpp_window != 0 );
::SetWindowSubclass(
window_handle_,
main_window_subclassproc,
subclass_id,
reinterpret_cast<DWORD_PTR>( cpp_window )
)
|| throw_x( "gui::api_level::window_subclass_t::<init>(): SetWindowSubclass failed" );
}
};
ATOM create_main_window_class()
{
WNDCLASS params = {};
params.hbrBackground = reinterpret_cast<HBRUSH>( COLOR_WINDOW + 1 );
params.hCursor = ::LoadCursor( 0, IDC_ARROW );
params.hIcon = ::LoadIcon( 0, IDI_APPLICATION );
params.hInstance = ::GetModuleHandle( nullptr );
params.lpfnWndProc = &::DefWindowProc;
params.lpszClassName = L"MainWindow";
ATOM const result = ::RegisterClass( ¶ms );
hopefully( result != 0 )
|| throw_x( "gui::api_level::create_main_window_class: RegisterClass failed" );
return result;
}
ATOM main_window_class()
{
static ATOM const the_class = create_main_window_class();
return the_class;
}
HWND create_main_window()
{
HWND const window = ::CreateWindow(
MAKEINTATOM( main_window_class() ),
L"My main window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
400, 300,
HWND(), // Parent.
HMENU(), // Menu.
::GetModuleHandle( nullptr ),
nullptr // Param.
);
hopefully( window != 0 )
|| throw_x( "gui::api_level::create_main_window: CreateWindow failed" );
return window;
}
} // api_level
class window_t
: private api_level::message_handler_t
{
private:
window_t( window_t const& ) IS_DELETED;
window_t& operator=( window_t const& ) IS_DELETED;
api_level::window_subclasser_t subclasser_;
virtual LRESULT window_proc( MSG const& m ) override
{
switch( m.message )
{
case WM_DESTROY:
delete this;
::PostQuitMessage( 0 );
return 0;
default:
return subclasser_.pass_to_superclass( m );
}
}
protected:
struct api_object_factory_t
{
virtual HWND create() const
{
return api_level::create_main_window();
}
};
virtual ~window_t() {}
window_t( api_object_factory_t const& factory )
: subclasser_( factory.create(), this )
{}
public:
HWND handle() const { return subclasser_.handle(); }
void show() { ::ShowWindow( handle(), SW_SHOW ); }
};
} // namespage gui
// ---------------------------------------------------------------------------------------
// Usage:
class main_window_t
: public gui::window_t
{
public:
main_window_t()
: gui::window_t( api_object_factory_t() )
{}
};
void cpp_main()
{
auto const main_window = new main_window_t();
main_window->show();
MSG msg;
while( winapi::get( msg ) )
{
::TranslateMessage( &msg );
::DispatchMessage( &msg );
}
assert( msg.message == WM_QUIT );
}
#include <iostream>
auto main() -> int
{
using namespace std;
try { cpp_main(); return EXIT_SUCCESS; }
catch( exception const& x ) { wcerr << "!" << x.what() << endl; }
return EXIT_FAILURE;
}
To compile this with Visual C++ 11.0, define the preprocessor symbol IS_DELETED as nothing.
i want to know if there's a way to print a jpg onto a picture control rectangle (that i build with ResEdit) the action that should print the image is case IDC_BUTTON1: and the target i want to view the image is in a picture control with the id: IDC_STATIC
BOOL CALLBACK AppDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_INITDIALOG:
DragAcceptFiles(hDlg,true);
SetClassLongPtr(hDlg, GCLP_HICON, (long)LoadIcon(0, IDI_APPLICATION));
return 1;
case WM_COMMAND:
switch(wParam)
{
case IDOK:
return 0;
case IDCANCEL:
EndDialog(hDlg, 0);
}
switch(wParam)
{
case IDC_BUTTON1:
ShellExecute(hDlg,
"open",
"C:\immagine1.jpg",
NULL,
NULL,
SW_SHOWDEFAULT);
break;
}
switch(wParam)
{
case IDC_BUTTON4:
ShellExecute(hDlg,
"open",
"C:\log.txt",
NULL,
NULL,
SW_SHOWDEFAULT);
break;
}
}
return 0;
}
instead of using shell execute that open the default viewer thank you all
The OleLoadPicturePath API function can load a JPEG file.
Then it's just a matter of accessing the bits.
There's also the Windows Imaging Component API, but I haven't used that.
I suspect that it also works, though, and it may be simpler than dealing with the OLE stuff, but here I exemplify OleLoadPicturePath.
Before trying to adapt the code below, you should:
Make sure that the type of the picture control resource is set to BITMAP (essentially, at the .rc text level, that it has the SS_BITMAP style).
Change the ID to something unique, instead of IDC_STATIC.
#include <header_wrapper/olectl_h.h> // IPicture
#include <header_wrapper/windows_h.h>
#include "resource.h" // IDD_DEMO_DIALOG, IDC_PICTURE
#include <progrock/cppx/throwx.h> // hopefully, throwX, std::exception
#include <progrock/cppx/size.h> // size
#include <progrock/winapi/path.h> // *
#include <progrock/winapi/ComPointer.h> // ComPointer
using namespace progrock;
#include <assert.h> // assert
#include <iostream>
#include <stdlib.h> // EXIT_FAILURE, EXIT_SUCCESS
using namespace std;
using cppx::hopefully;
using cppx::size;
using cppx::throwX;
using winapi::String;
struct IsHrSuccess
{
friend bool operator>>( HRESULT const hr, IsHrSuccess const& )
{
return SUCCEEDED( hr );
}
};
IsHrSuccess const isHrSuccess = IsHrSuccess();
short kindOf( IPicture const& pic )
{
short kind = 0;
const_cast< IPicture& >( pic ).get_Type( &kind )
>> isHrSuccess || throwX( "kindOf: IPicture::get_Type failed" );
return kind;
}
bool isBitmap( IPicture const& pic )
{
return (kindOf( pic ) == PICTYPE_BITMAP);
}
OLE_HANDLE handleOf( IPicture const& pic )
{
OLE_HANDLE result = 0;
const_cast< IPicture& >( pic ).get_Handle( &result )
>> isHrSuccess || throwX( "handleOf: IPicture::get_Handle failed" );
return result;
}
HBITMAP bmpHandle( IPicture const& pic )
{
assert( isBitmap( pic ) );
return reinterpret_cast< HBITMAP >( handleOf( pic ) );
}
namespace g {
winapi::ComPointer<IPicture> pPicture;
} // namespace g
INT_PTR CALLBACK demoDialogProc(
HWND const window,
UINT const messageId,
WPARAM const wParam,
LPARAM const lParam
)
{
switch( messageId )
{
case WM_INITDIALOG:
::SendDlgItemMessage(
window, IDC_PICTURE, STM_SETIMAGE,
IMAGE_BITMAP,
reinterpret_cast< LPARAM >( bmpHandle( *g::pPicture ) )
);
break;
case WM_CLOSE:
::EndDialog( window, IDCANCEL );
break;
case WM_COMMAND:
::EndDialog( window, wParam );
break;
}
return 0;
}
struct Com
{
Com() { ::CoInitialize( 0 ) >> isHrSuccess || throwX( "::CoInitialize failed" ); }
~Com() { ::CoUninitialize(); }
};
void cppMain()
{
Com usingCom;
String const picFileName = L"image.jpg";
String const picFilePath = winapi::path::combine( winapi::exeFolder(), picFileName );
::OleLoadPicturePath(
const_cast< wchar_t* >( picFilePath.c_str() ),
nullptr, 0, 0,
IID_IPicture,
g::pPicture.asOutArgument()
)
>> isHrSuccess || throwX( "OleLoadPicturePath failed" );
assert( isBitmap( *g::pPicture ) );
::DialogBox( ::GetModuleHandle( 0 ), MAKEINTRESOURCE( IDD_DEMO_DIALOG ), 0, demoDialogProc );
}
int main()
{
try
{
cppMain();
return EXIT_SUCCESS;
}
catch( exception const& x )
{
wcout << "!" << x.what() << endl;
}
return EXIT_FAILURE;
}
I am using FindWindow in an mfc application.
HWND hWnd = ::FindWindow(NULL, _T("foobar v5"));
I would like to use FindWindow with wildcards so that I can match just foobar.
Thanks
You will have to create your own implementation which should be based on EnumWindows, GetWindowText and GetWindowTextLength which then must allow the wildcards.
#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>
struct FindWindowData {
FindWindowData( TCHAR const * windowTitle )
: WindowTitle( windowTitle )
, ResultHandle( 0 )
{}
std::basic_string<TCHAR> WindowTitle;
HWND ResultHandle;
};
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 ) {
std::vector<TCHAR> buffer( std::size_t( length ), 0 );
if( GetWindowText( hWnd, &buffer[0], length ) ) {
// Comparing the string - If you want to add some features you can do it here
if( _tcsnicmp( &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;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "HWND: " << FindWindowStart(TEXT("foobar ") );
std::cout << " GetLastError() = " << GetLastError() << std::endl;
return 0;
}
Unfortunately, FindWindow() does not support wildcards.
Did you try matching the window class name instead of its title? You can use a tool like Spy++ to find out the class name of the foobar main window.