Quantcast
Channel: Visual C forum
Viewing all 15302 articles
Browse latest View live

Debug assertion failed! MFC Application Visual studio 2015 c++

$
0
0

I am new to visual studio and I want to create a simple mfc application with a combo box selection. 

// MFCApplicationTestDlg.cpp : implementation file
//

#include "stdafx.h"
#include "MFCApplicationTest.h"
#include "MFCApplicationTestDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
    CAboutDlg();

// Dialog Data
#ifdef AFX_DESIGN_TIME
    enum { IDD = IDD_ABOUTBOX };
#endif

    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
    DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CMFCApplicationTestDlg dialog



CMFCApplicationTestDlg::CMFCApplicationTestDlg(CWnd* pParent /*=NULL*/)
    : CDialogEx(IDD_MFCAPPLICATIONTEST_DIALOG, pParent)
{
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMFCApplicationTestDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CMFCApplicationTestDlg, CDialogEx)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_CBN_SELCHANGE(IDC_COMBO1, &CMFCApplicationTestDlg::OnCbnSelchangeCombo1)
    ON_CBN_SELENDOK(IDC_COMBO1, &CMFCApplicationTestDlg::OnCbnSelendokCombo1)
END_MESSAGE_MAP()


// CMFCApplicationTestDlg message handlers

BOOL CMFCApplicationTestDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // Add "About..." menu item to system menu.

    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);         // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon

    // TODO: Add extra initialization here
    CComboBox *combo = new CComboBox();
    combo->AddString(L"csv1.csv");
    combo->AddString(L"csv2.csv");
    combo->AddString(L"csv3.csv");


    return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMFCApplicationTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID & 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {
        CDialogEx::OnSysCommand(nID, lParam);
    }
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMFCApplicationTestDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // device context for painting

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

        // Center icon in client rectangle
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;

        // Draw the icon
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialogEx::OnPaint();
    }
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMFCApplicationTestDlg::OnQueryDragIcon()
{
    return static_cast<HCURSOR>(m_hIcon);
}



void CMFCApplicationTestDlg::OnCbnSelchangeCombo1()
{
    // TODO: Add your control notification handler code here
    CString csv[] = { _T(""), _T("csv1.csv"),_T("csv2.csv"),_T("csv3.csv") };
    UpdateData(FALSE);
}


void CMFCApplicationTestDlg::OnCbnSelendokCombo1()
{
    CComboBox *combo1 = new CComboBox();
    CString file;
    int n;
    // TODO: Add your control notification handler code here
    int index = combo1->GetCurSel();
    combo1->GetLBText(index, file);

}


It was working till yesterday and I was just wondering how to display the string. But today I have got this problem which says


Debug Assertion failed!

Program:
...Root\MFCApp\MFCApplicationTest2\Debug\MFCApplicationTest2.exe
File:f:\dd\vctools\cv7libs\shop\atlmfc\include\afxwin2.inl
Line: 795

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Please retry to debug the application)

And when I click retry I get this,

MFCApplicationTest2.exe has triggered a breakpoint.


breaking this takes me to this line of assertion failure,

	{ ASSERT(::IsWindow(m_hWnd)); return (int)::SendMessage(m_hWnd, CB_ADDSTRING, 0, (LPARAM)lpszString); }

I checked this post which is related to my question on the topic on this forum,

MFX CComboBox assert error doing AddString

and I noticed that I haven't made that mistake. But then if I keep retrying and hit continue it takes me to the output.

I am not sure what the problem is. Please do help. 


How to identify the unresponsive state of an exe ?

$
0
0

Hi All,

We are having an application developed with Visual Studio 2012 (VC++) and this is a Windows service based application. In this application, one exe (example MyApp1.exe) is running on the SYSTEM account (handling service related functionalities) and another exe (MyApp2.exe) is running on each User Sessions (User Account).

We need to identify the unresponsive state of MyApp2.exe (an instance of the currently active user) from MyApp1.exe. So anyone please help us to create the functionalities for identifying the same.

Thanks in advance.

Regards,

R-V-R


How to define a GIF image in resource file?

$
0
0

I am trying to load a GIF image file using GDI+, is the code below a right way to define a GIF image in .rc file?

Thanks in advance.

IDB_THICKNESSXY			GIF					"ThicknessXY_test.gif"

Why does CString.Empty() or CString = L"" cause garbage in the variable?

$
0
0

Hi,

I'm having an odd problem. It's only happen with one particular solution and when I try this in another, smaller, solution it appears to work fine. However in my larger solution if I define a CString as:

CString sTestString;

Looking at it in the debugger I see that the value of sTestString right after being defined is the executable path of the .exe I'm running. If I try to empty it, either with .Empty() or '= L"";', even if there was some other value in the string prior to emptying it, after the empty the string contains the executable path. 

Has anyone else seen anything like this?

Thanks,

Rob

How to get filename from resource ID?

$
0
0

I am trying to display a GIF image in a static control. The GIF image is loaded using GDI+, it needs the image filename passed to the image construction, I want to obtain the filename from the resource ID, but I could not get it from the code below.

Any suggestion would be appreciated.

HBITMAP ctrlBitmap(NULL);

Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); LPCTSTR lpszResourceName = MAKEINTRESOURCE(IDB_THICKNESSXY); ASSERT(lpszResourceName != NULL); HINSTANCE hInst = AfxFindResourceHandle(lpszResourceName, RT_RCDATA); HRSRC hResInfo = ::FindResource(hInst, lpszResourceName, RT_RCDATA); HGLOBAL hResData = ::LoadResource(hInst, hResInfo); char* data = (char*)(::LockResource(hResData)); DWORD len = ::SizeofResource(NULL, hResInfo); CString filename(data, len); Gdiplus::Bitmap* bitmap = new Gdiplus::Bitmap(filename); Gdiplus::Status status = bitmap->GetHBITMAP(NULL, &ctrlBitmap); Gdiplus::GdiplusShutdown(gdiplusToken);

GetParent()->GetPropertySheet()->SetControlImage(ctrlBitmap);


msvcr80.dll

$
0
0

 

Dear Customer,
 
Please go to the following link and login with Username: "csupport" Password: "elsevier1"
 
 
Please locate the  folder titled "MSVCR80". Copy and paste the folder to your computer desktop.
Once on the desktop, double click on the folder and locate the MSVCR80.DLL icon. Right-click the icon
and select copy (If copy is not an available option,you must click the "PAGE" button on the upper right side
of Internet Explorer and select "Open FTP site in Windows Explorer". You will then need to sign in again.
This should now allow you to select copy from the right click menu. You do not want to select "copy shortcut").
Next, right click on the Start button and select Explore. This will open Windows Explorer. Please locate the
folder "Windows" and click on the + sign next to Windows to expand. Locate the folder "System32"
and click to highlight.In the right side frame (System32 folder), right-click and
select paste. This will place the MSVCR80.DLL file into the System32 folder. You can now close
Windows Explorer. Try running the program again. This should resolve your error.
If you need further assistance please don't hesitate to call or email me.
 
Thank you,

MFC DLL load from Win32 App -> Memory Leaks

$
0
0

I hope i'm clear to post the problem.  I'm using Visual Studio 2003 SP1. The main application is a simple Win32 application that link dinamically a MFC dll. In some case when a try to execute FreeLibrary of the dll previusly loaded by LoadLibrary i get a memory leaks. For example in this code :

a=new int [100];
hmod=LoadLibrary(FILEDLL);
FreeLibrary(hmod);
delete [] a;

when i execute the FreeLibrary i get this memory dump:

"TestLoadFree.exe": Load"C:\.......\TestMemLeaks.dll", ....
"TestLoadFree.exe": Load"C:\WINDOWS\system32\mfc71d.dll", ....
"TestLoadFree.exe": Load"C:\WINDOWS\system32\MFC71ITA.DLL", ....

Detected memory leaks!
Dumping objects ->
{60} normal block at 0x00852C88, 400 bytes long.
Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
"TestLoadFree.exe": Unload"C:\.......\TestMemLeaks.dll"
"TestLoadFree.exe": Unload"C:\WINDOWS\system32\mfc71d.dll"
"TestLoadFree.exe": Unload"C:\WINDOWS\system32\MFC71ITA.DLL

 

It seems a Fake memory leaks .. but i'm not sure. ! So i added the ExitInstance handler of MFC dll to verify when the memory leaks is fired:

int CTestMemLeaksApp::ExitInstance()
{
  TRACE(_T("Start ExitInstance() for regular DLL: TESTDLL\n"));
  int retvalue=CWinApp::ExitInstance();
  TRACE(_T("End ExitInstance() for regular DLL: TESTDLL\n"));
  return retvalue;
}

and i get this memory dump:

"TestLoadFree.exe": Load"C:\.......\TestMemLeaks.dll", ....
"TestLoadFree.exe": Load"C:\WINDOWS\system32\mfc71d.dll", ....
"TestLoadFree.exe": Load"C:\WINDOWS\system32\MFC71ITA.DLL", ....

Start ExitInstance() for regular DLL: TESTDLL
End ExitInstance() for regular DLL: TESTDLL


Detected memory leaks!
Dumping objects ->
{60} normal block at 0x00852C88, 400 bytes long.
Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
"TestLoadFree.exe": Unload"C:\.......\TestMemLeaks.dll"
"TestLoadFree.exe": Unload"C:\WINDOWS\system32\mfc71d.dll"
"TestLoadFree.exe": Unload"C:\WINDOWS\system32\MFC71ITA.DLL"

the debbugger write the memory dump when the FreeLibrary is called ...
It is clear that the memory leaks is related to a pointer allocation. But it is not clear because the memory leak is present! I suspect to some not right settings of two project... But the main application is a Win32 application with Code generation = Debug Multithreaded DLL, while the dll mfc use the same code generation setting and the MFC is used in shared mode (Use MFC in Shared DLL). I think it is all right .. but the memory leaks is again there!

If it is useful i can post the entire two project (both are near to the code generate by wizard  )

Thank in advance!

 

 

 

Memory leaks on IUIAutomationEventHandler

$
0
0

I have made a sample app, SDI, where I run a thread with IUIAutomationEventHandler:

UINT __stdcall UIAMonitor(LPVOID pv);

class CEventHandler : public IUIAutomationEventHandler
{
public:
	CEventHandler(IUIAutomation* pAuto, IUIAutomationCacheRequest* pBCache, IUIAutomationCondition* pBCond);
	STDMETHOD (QueryInterface)(REFIID riid, void** ppv);
	STDMETHOD_(ULONG, AddRef)();
	STDMETHOD_(ULONG, Release)();
	STDMETHOD(HandleAutomationEvent)(IUIAutomationElement* sender, EVENTID eventId);

private:
	~CEventHandler();
	LONG m_cRef;
	IUIAutomation* m_pAuto;
	IUIAutomationCacheRequest* m_pButtonCacheRequest;
	IUIAutomationCondition* m_pBCond;
};


and in OnInitialUpdate a start the thread:

void CTTTView::OnInitialUpdate()
{
	CHtmlView::OnInitialUpdate();

	HANDLE hThread = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, UIAMonitor, &m_hEvent.m_h, 0, nullptr));
	if (hThread)
	{
		CloseHandle(hThread);
	}
	else
	{
		MessageBox(_T("Failed to create UIAMonitor thread"), NULL, MB_ICONERROR);
	}

	SetSilent(TRUE);
	Navigate2(_T("https://www.codeproject.com"));
}

and here is the UIAMonitor function:

UINT __stdcall UIAMonitor(LPVOID pv)
{
	HRESULT hres, hr = E_FAIL;
	HANDLE hEvent = *(static_cast<PHANDLE>(pv));
	if (SUCCEEDED(hres = CoInitializeEx(NULL, COINIT_MULTITHREADED)))
	{
		CComPtr<IUIAutomation> pAutomation;
		hr = CoCreateInstance(CLSID_CUIAutomation, NULL, CLSCTX_INPROC_SERVER, IID_IUIAutomation, reinterpret_cast<LPVOID*>(&pAutomation));
		if (pAutomation)
		{
			CComPtr<IUIAutomationElement> pRoot;
			CComPtr<IUIAutomationCacheRequest> pButtonCacheRequest;
			CComPtr<IUIAutomationCondition> pCondButton;
			CComPtr<IUIAutomationEventHandler> pHandler;
			CComVariant vButton(UIA_ButtonControlTypeId);
			hr = pAutomation->CreateCacheRequest(&pButtonCacheRequest);
			if (pButtonCacheRequest)
			{
				hr = pButtonCacheRequest->AddProperty(UIA_NamePropertyId);
				hr = pButtonCacheRequest->AddProperty(UIA_AutomationIdPropertyId);
				hr = pButtonCacheRequest->AddPattern(UIA_InvokePatternId);
			}
			hr = pAutomation->CreatePropertyCondition(UIA_ControlTypePropertyId, vButton, &pCondButton);
			if (pCondButton && pButtonCacheRequest)
			{
				CEventHandler* pEventObject = new CEventHandler(pAutomation, pButtonCacheRequest, pCondButton);  // <--- memory leaks
				if (pEventObject)
				{
					hr = pEventObject->QueryInterface(IID_PPV_ARGS(&pHandler));
					pEventObject->Release();
				}
				if (pHandler)
				{
					hr = pAutomation->GetRootElement(&pRoot); // Receive window events for all new windows created under the desktop
					if (pRoot)
					{
						hr = pAutomation->AddAutomationEventHandler(UIA_Window_WindowOpenedEventId, 
							pRoot, TreeScope_Descendants, NULL, pHandler);
					}
				}
			}
			DWORD dwWake = WaitForSingleObject(hEvent, INFINITE);  // Keeps event handler 7 seconds /*alive until program terminates*/
			ATLASSERT(dwWake == WAIT_OBJECT_0);
			hr = pAutomation->RemoveAllEventHandlers();
		}
	}

	if (SUCCEEDED(hres))
		CoUninitialize();

	return hr;
}

the problem is that sometime, not all the time, at application exit, I got memory leaks:

Dumping objects ->
d:\tempx\ttt\uiaeventmonitor.cpp(34) : {25387} normal block at 0x059D9528, 20 bytes long.
 Data: <  (          z  > 0C DA 28 01 02 00 00 00 D8 98 EA 00 98 7A EB 00 
Object dump complete.

And here is where I setup, ans stop the thread:

CTTTView::CTTTView()
{
	// TODO: add construction code here

	m_hEvent.Attach(CreateEvent(NULL, FALSE, FALSE, NULL)); // Automatic reset, not signalled
}

void CTTTView::OnDestroy()
{
	SetEvent(m_hEvent);  // signal UIAMonitor thread to exit

	CHtmlView::OnDestroy();

	// TODO: Add your message handler code here
}

I say again: sometime I got ML, sometime not ... which indicate that something is not right ... I attach asample project to illustrate this behavior ... can you tell me what I have done wrong here ? Thank you.



How to Determine the Type of Exception?

$
0
0

Hi

 

When debugging program in Visual C++ 2008, I get an exception said “Microsoft C++ exception: COleDispatchException at memory location 0x####”. Based on this info, I add a try-catch block as follows:

 

try

{

 

Do something

}

Catch(COleDispatchException& e)

{

}

 

But this does not catch the exception. Then I change the parameter from COleDispatchException& to COleDispatchException*, as follows:

 

try

{

 

Do something

}

Catch(COleDispatchException* e)

{

}

 

Then I will be able to catch the exception. So I just wonder how to know the exception type beforehand, to prevent taking time to guess the type?

Error message

$
0
0
I keep getting an error message saying "This program can't start because api-ms-win-crt-heap-l1-1-0.dll is missing from your computer. Try reinstalling the program to fix this problem." I then click "OK", another message pops up saying"Failed to locate Framework DLL". I recently did a factory reset on my hp laptop and my windows is up to date 8.1, I am trying to use the silhouette studio software. Can anyone help me figure out how to get it to work?

Writing on an usb flash drive using its device path

$
0
0

Hello everyone!

Using the SetupAPI and more precisely the SetupDiGetDeviceInterfaceDetail function I am able to get the device path to my usb flash drive: \\?\usbstor#disk&ven_sandisk&prod_cruzer&rev_8.02#35151307ca62eb53&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}

The SetupDiGetDeviceInterfaceDetail doc states that "The interface detail returned by this function consists of a device path that can be passed to Win32 functions such as CreateFile" but I was unable to open any file on my usb flash drive.

Am I misunderstanding something or doing it wrong ?

My code responsible for enumerating the drives:

#include "stdafx.h"


int main() {
	GUID classGuid = GUID_DEVINTERFACE_DISK; // We only want disks
	SP_DEVICE_INTERFACE_DATA devInterfaceData;
	PSP_DEVICE_INTERFACE_DETAIL_DATA_A pDevInterfaceDetailData;
	DWORD devInterfaceDetailDataSize;

	HDEVINFO devInfoSet = SetupDiGetClassDevsA(&classGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if (devInfoSet == INVALID_HANDLE_VALUE) {
		SetupDiDestroyDeviceInfoList(devInfoSet);
		printf("Error with SetupDiGetClassDevsW");

		return 1;
	}

	devInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
	for (int i = 0; SetupDiEnumDeviceInterfaces(devInfoSet, NULL, &classGuid, i, &devInterfaceData); i++) {
		devInterfaceDetailDataSize = 0;
		if (!SetupDiGetDeviceInterfaceDetailA(devInfoSet, &devInterfaceData, NULL, 0, &devInterfaceDetailDataSize, NULL)) {
			/*SetupDiDestroyDeviceInfoList(devInfoSet);
			printf("Error getting SP_DEVICE_INTERFACE_DETAIL_DATA_A size, error %lu", GetLastError());

			return 1;*/
		}

		pDevInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA_A)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, devInterfaceDetailDataSize);
		if (!pDevInterfaceDetailData) {
			SetupDiDestroyDeviceInfoList(devInfoSet);
			printf("Error allocating SP_DEVICE_INTERFACE_DETAIL_DATA_A");
			return 1;
		}

		pDevInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
		if (!SetupDiGetDeviceInterfaceDetailA(devInfoSet, &devInterfaceData, pDevInterfaceDetailData, devInterfaceDetailDataSize, NULL, NULL)) {
			/*SetupDiDestroyDeviceInfoList(devInfoSet);
			HeapFree(GetProcessHeap(), NULL, pDevInterfaceDetailData);
			printf("Error retrieving SP_DEVICE_INTERFACE_DETAIL_DATA_A");*/

			return 1;
		}

		printf("Path: %s\n", pDevInterfaceDetailData->DevicePath);

		HeapFree(GetProcessHeap(), NULL, pDevInterfaceDetailData);
	}
	SetupDiDestroyDeviceInfoList(devInfoSet);

    return 0;
}

To test the path I made this code that prints the size of a given file:

#include "stdafx.h"


int main(int argc, char * argv[]) {
	HANDLE hFile;
	LPWSTR lpwsError;
	ULONGLONG fileSize;


	if (argc != 2) {
		printf("No file path supplied!");
	}

	hFile = CreateFileA(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if (hFile == INVALID_HANDLE_VALUE) {
		FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
			MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPWSTR)&lpwsError, 200, NULL);
		printf("%ws", lpwsError);
		LocalFree(lpwsError);
		return 1;
	}

	LARGE_INTEGER largeSize;
	if (!GetFileSizeEx(hFile, &largeSize)) {
		FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
			MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPWSTR)&lpwsError, 200, NULL);
		printf("%ws", lpwsError);
		LocalFree(lpwsError);
		return 1;
	}

	fileSize = largeSize.QuadPart;
	printf("File size: %llu", fileSize);

    return 0;
}

Thank you advance for your contribution.

How to display an animated GIF image in a static control?

$
0
0

I can display a bitmap image without animation in a static control.

How to display a GIF image with animation in a static control? The GIF image is loaded with GDI+ in the code below, but only a static image of the first frame of the GIF is displayed, there is no animation. How to display the animation in GIF?

HBITMAP ctrlBitmap(NULL);

Gdiplus::Bitmap* pBitmap = NULL;
pBitmap = new Gdiplus::Bitmap(pStream);
pBitmap->GetHBITMAP(NULL, &ctrlBitmap);

CStatic m_ctrlImage;
m_ctrlImage.Create(NULL, WS_CHILD | SS_BITMAP | WS_VISIBLE | SS_REALSIZEIMAGE | SS_CENTERIMAGE | WS_BORDER, rectImage, this, IDC_IMAGE);
::SendMessage(m_ctrlImage, STM_SETIMAGE, IMAGE_BITMAP,(LPARAM)(HBITMAP)ctrlBitmap);
Thanks in advance.


IHTMLInputFileElement put_value

$
0
0

I am struggle for a while to put a text inside file input tag in html, using CHtmlView. And I succeeded for any kind of input type, but not for file input type: I have the following html code:

<span>Choose the file:</span> <span> <input type="file" name="linkdoc" size="75" value=""></span><span><input type="submit" value="Send"></span>


and the MFC code:

								IHTMLInputFileElement* pInputElem = NULL;
								hr = pElemDispatch->QueryInterface(IID_IHTMLInputFileElement, (void**)&pInputElem);
....
....
											CString sTemp(sNewValue);
											BSTR bstrNewValue = sTemp.AllocSysString();
											pInputElem->put_value(bstrNewValue);
											SysFreeString(bstrNewValue);

but it simply not change the value ...

I have read the html IHTMLInputFileElement documentation:

IHTMLInputFileElement::put_value
HRESULT put_value(
    BSTR v
);
Sets the value of the INPUT file control.

Returns S_OK if successful, or an error value otherwise.
v
String specifying the value.
but is not working ... can anybody tell me how to solve this ? In deed, manually I cannot change this input type valus, only if I go with "Browse" button, and so on ... but my task is to change this value programmatically by my code.

[C++] [Win32] [DirectX11] SetFullscreenState & ResizeBuffers question

$
0
0

Hi everybody,

first off all: I hope I reached the right forum ( did not find one for DirectX ) - if not: SORRY !!

I'm struggling since three days with a directX problem and now I think it's time to ask the experts:

I want to react to ALT-TAB in a Win32 / DirectX 11 programm, by using the messages WM_KILLFOCUS and WM_SETFOCUS.

( First ALT-TAB: switches to windowed, second one: switch back to fullscreen )

According to the following microsft article:

https://docs.microsoft.com/de-de/windows/desktop/direct3darticles/dxgi-best-practices#full-screen-issues

I only have to call: SetFullscreenState, resize the buffers ( as an answer to WM_SIZE ) and here we go:

DXGI resizes the front buffer to match the newly selected full-screen mode, and it sends a WM_SIZE message to the application. The application again callsResizeBuffers, just as it would if the window border was dragged.

I'm calling the following:

m_swapChain->SetFullscreenState(fullscreen, nullptr);

where "fullscreen" is a bool that say's: Yes fullscreen, or No Windowed

And here's what I'm calling on WM_SIZE:

if (FAILED(m_swapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH))) throw ref new Platform::FailureException("Resize Buffers failed");

Result: I'm getting an error for the Resize call:

Swapchain cannot be resized unless all outstanding buffer references have been released. [ MISCELLANEOUS ERROR #19: ]

Is it really true ?

Do I have to release all buffers and create them new ?

But why should I use ResizeBuffers, if I have to make it all manually ?

Any ideas ?

Thanks,

Charlie Brown

no Images on toolbar buttons

$
0
0

Here is my function for the toolbar creation. Image is a bitmap created with VS toolbar editor. Also, I'm unclear how the linker associates my bitmap with the #define in the .h file. Some magic when the .rc file is linked in?

void c_CharEditWindow::Toolbar()
{
	HIMAGELIST g_hImageList = NULL;

	hwndToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL, WS_CHILD | TBSTYLE_WRAPABLE,
		0, 0, 0, 0, m_hwnd, NULL, GetModuleHandle(NULL), NULL);

	g_hImageList = ImageList_Create(22, 22, ILC_COLOR16 | ILC_MASK, 4, 0);

	SendMessage(hwndToolbar, TB_SETIMAGELIST, 0, (LPARAM)g_hImageList);

	SendMessage(hwndToolbar, TB_LOADIMAGES, (WPARAM)IDR_TOOLBAR1, (LPARAM)GetModuleHandle(NULL));

	TBBUTTON tbButtons[4] = {
	{ID_BUTTON40002, WM_MOVE, TBSTATE_ENABLED, BTNS_AUTOSIZE, {0}, 0, NULL },
	{ MAKELONG(ID_BUTTON40003, 0), WM_MOVE, TBSTATE_ENABLED, BTNS_AUTOSIZE, { 0 }, 0, NULL },
	{ MAKELONG(ID_BUTTON40004, 0), WM_MOVE, TBSTATE_ENABLED, BTNS_AUTOSIZE, { 0 }, 0, NULL },
	{ MAKELONG(ID_BUTTON40005, 0), WM_MOVE, TBSTATE_ENABLED, BTNS_AUTOSIZE,{ 0 }, 0, NULL }
	};

	SendMessage(hwndToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
	SendMessage(hwndToolbar, TB_ADDBUTTONS, 4, (LPARAM)&tbButtons);
	SendMessage(hwndToolbar, TB_AUTOSIZE, 0, 0);

	ShowWindow(hwndToolbar, TRUE);

}
I only get blank buttons.



About function CreateFontPackage on TTC data

$
0
0
   unsigned short usFlag = TTFCFP_FLAGS_SUBSET | TTFCFP_FLAGS_TTC;
   unsigned short usTTCIndex = 0;
   unsigned short usSubsetFormat = TTFCFP_SUBSET;
   unsigned short usSubsetLanguage = 0;
   unsigned short usSubsetPlatform = TTFCFP_MS_PLATFORMID;
   unsigned short usSubsetEncoding = TTFCFP_DONT_CARE;

long ret = CreateFontPackage(&fontData[0],      // input ttf or ttc buffer
                                srcBufferSize,     // input buffer size
                                &pOutBuffer,       // output package buffer
                                &outBufferSize,    // output package buffer size
                                &outBufferWritten, /* output package buffer data length */
                                usFlag,            /* subset, compress, or both, TTF or TTC, Chars or Glyphs */
                                usTTCIndex,        /* TTC Index, only used if TTC bit set */
                                usSubsetFormat,    /* Old Subset, Subset or Delta */
                                usSubsetLanguage,  /* Language in Name table to keep */
                                usSubsetPlatform,  /* if ListType is Character, Platform of cmap to use for glyph list */
                                usSubsetEncoding,  /* if ListType is Character, Encoding of cmap to use for glyph list */
                                &text[0],          /* List of Characters or Glyphs to keep */
                                4,                  /* number of elements in list */
                                malloc, realloc, free,    /* call back functions about memory operations */
                                NULL);

always got the ret with 1106, means the Calling function parameter 6 was invalid, what the meaning of usTTCIndex, how to set it value?

VS2013 "SetSite failed for package"

$
0
0
Today Visual Studio 2013 refuses to load my .sln files.    The activity log tells me ERROR "SetSite failed for package [Visual C++ Project System Package]".   It worked fine yesterday.

What do I do?

[I note that at least two Windows 10 Updates have just arrived:  "Security Update for Adobe Flash Player" and "Cumulative Update for Windows 10 Version 1803 for x-64 based systems (KB4338832)".  Has one of these buggered it?]

David Webber Author of Mozart music notation software http://www.mozart.co.uk

Anomaly when Enumerating Processes

$
0
0

I am working on a program that should work in parallel with another one ("Logos").  To accomplish this, it will connect to that program via COM interface.  The idea is that if Logos is running, my program will communicate with it, but if Logos is not running, my program will work independently.

My program contains the following function:

bool FindProcess(CString sought)
{
  bool result = false;
  DWORD aProcesses[1024], cbUsed, cProcessesFound;
  unsigned int i;

  // Get the list of process identifiers.
  if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbUsed))
    return result;

  // Calculate how many process identifiers were returned.
  cProcessesFound = cbUsed / sizeof(DWORD);

  TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
  CString tempStr;

  // send trace data to output window
  tempStr.Format(L"%d Processes:", cProcessesFound);
  TRACET(tempStr); TRACEN;
  tempStr = L"\t#\tPID\tName";
  TRACET(tempStr); TRACEN;

  // search list of process ids for process name
  for (i = 0; i < cProcessesFound; i++)
  {
    if (aProcesses[i] != 0)
    {
      // Get process handle
      HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                    FALSE, aProcesses[i]);

      // if process can be opened (some system processes are protected)
      if (NULL != hProcess)
      {
        HMODULE hMod;
        DWORD cbUsed;

        // instead of enumerating all modules for this process, only
        // get 1st one - the .exe
        if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbUsed))
        {
          // Get module's base name
          GetModuleBaseName(hProcess, hMod, szProcessName,
                    sizeof(szProcessName) / sizeof(TCHAR));

          tempStr.Format(L"%d:\t%d\t%s", i, aProcesses[i], szProcessName);
          TRACET(tempStr); TRACEN;

          // if module name matches what we're looking for
          if (!sought.CompareNoCase(szProcessName))
          {
            result = true;
            break;
          }
        }
      }

      // Release process handle
      CloseHandle(hProcess);
    }
  }

  return result;
}
When this function runs, it fails to find the Logos process.  Here is the output:

226 Processes:
#PIDName
105:7912 MotoHelperAgent.exe
115:5436 CLMLSvc_P2G8.exe
131:10908 AirDroid.exe
134:10452 ISBMgr.exe
135:10664 AvastUI.exe
136:8724 PMBVolumeWatcher.exe
138:9756 BrStMonW.exe
139:10684 BrotherHelp.exe
142:12208 pptd40nt.exe
144:11792 PdfPro7Hook.exe
146:6616 IAStorIcon.exe
180:6956 devenv.exe
181:6188 PerfWatson2.exe
182:6128 ServiceHub.Host.Node.x86.exe
184:12496 ServiceHub.IdentityHost.exe
185:8284 ServiceHub.Host.CLR.x86.exe
186:2824 ServiceHub.SettingsHost.exe
187:12108 ServiceHub.VSDetouredHost.exe
189:7588 Notepad++Portable.exe
190:9164 notepad++.exe
200:17668 AirDroidHelper.exe
205:17312 VCPkgSrv.exe
213:12700 BART5-4.exe

#213 is the running program which is enumerating the processes.

Here is a snippet from Task Manager, showing the Logos process:

Task Manager Processes tab

I tried a modification to my function in order to use a different approach to getting the module names:
bool FindProcess(CString sought)
{
  bool result = false;
  DWORD aProcesses[1024], cbUsed, cProcessesFound;
  unsigned int i;

  // Get the list of process identifiers.
  if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbUsed))
    return result;

  // Calculate how many process identifiers were returned.
  cProcessesFound = cbUsed / sizeof(DWORD);

  // search list of process ids for process name
  TCHAR szPathName[MAX_PATH] = TEXT("<unknown>");
  CString pathName, moduleName;
  int pathEndOffset;
  for (i = 0; i < cProcessesFound; i++)
  {
    if (aProcesses[i] != 0)
    {
      // Get process handle
      HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                    FALSE, aProcesses[i]);

      // if process can be opened (some system processes are protected)
      if (NULL != hProcess)
      {
        HMODULE hMod;
        DWORD cbUsed;

        // instead of enumerating all modules for this process, only
        // get 1st one - the .exe
        if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbUsed))
        {
          // Get module's file name
          GetModuleFileName(hMod, szPathName,
                    sizeof(szPathName) / sizeof(TCHAR));

          // if a file name was returned
          if (wcslen(szPathName))
          {
            // offset of beginning of file name (i.e. end of path)
            pathEndOffset = wcsrchr(szPathName, '\\') - szPathName;
            pathName = szPathName;
            moduleName = pathName.Right(pathName.GetLength() - pathEndOffset);

            // if module name matches what we're looking for
            if (!sought.CompareNoCase(moduleName))
            {
              result = true;
              break;
            }
          }
        }
      }

      // Release process handle
      CloseHandle(hProcess);
    }
  }

  return result;
}
When I ran this, only the name of my own program was found; all other processes had no name (i.e. empty string).

Can anyone offer a suggestion why I can't see the same processes as Task Manager?  (I know that system processes are protected, but what about the others?)  Is there any way I can revise FindProcess() in order to accomplish my objective?

string storage

$
0
0

I'm needing to pile up an unknown number of fixed length strings of data (34 characters each) and am currently just adding to the end of a std::string.At some points this string could get piled as high as several thousand, making the std::string over maybe as much as several thousand characters long.  Would I improve the speed or performance by turning it into an array of std::strings instead and putting a limit on it beforehand (say std::string[67000] or so)  ? 

I'm not using a database program for good reasons, and all the data in the string is also stored to a binary file; but I keep the string in memory for quick access to any part of it...

Font file can not load correctly by using AddFontMemResourceEx/AddFontResourceEx

$
0
0

I have a font file (.ttf), but I can not load correctly it by using API like  AddFontMemResourceEx/AddFontResourceEx, although these functions return the sucessfully. 

but there is no character in this font when I using the function GetFontUnicodeRanges 

but I can install it by just double click it and can be verify it's installed correctly.

I also try to use the MS Font Validator, and the result shows about cmap:

P0312The table version number is 0
P0307Each subtable offset is within the table
P0306Each subtable length is within the table
P0309The subtables are in the correct order
P0302There are no duplicate subtables
P0308No overlapping subtables were found
P0310Each subtable's format number is valid
W0306The format is 12, but the encoding id is not 10PlatID = 0, EncID = 3, Fmt = 12
P0305The subtable internal format appears validPlatID = 0, EncID = 3, Fmt = 12
P0305The subtable internal format appears validPlatID = 3, EncID = 1, Fmt = 4
W0302The table does not contain any Apple subtables
W0301Apple logo mapping test not performed, cmap 1,0 not present
W0305Character code U+20AC, the euro character, is not mapped in cmap 3,1
P0311No characters are mapped in the Unicode Private Use area
P0314

All non mac subtables have a language field of zero

can someone help me to take a look at it?

thanks


Viewing all 15302 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>