Does MFC provide a quick way to throw text on the clipboard? - mfc

The add-to-clip-board code we have in our code base is quite low-level - allocating global memory and so on. For the simple case I just want to put some plain text on the clipboard, are there any routines which can wrap all that stuff?
An example is that CRichEditCtrl has Copy() & Cut() methods which automatically put the current selection on the clipboard. Does MFC make this kind of functionality available in isolation?
Update: Created a new question based on mwigdahl's response

No, but it's not that hard to wrap it yourself. Adapted from Frost Code (and untested):
void SetClipboardText(CString & szData)
{
HGLOBAL h;
LPTSTR arr;
h=GlobalAlloc(GMEM_MOVEABLE, szData.GetLength()+1);
arr=(LPTSTR)GlobalLock(h);
strcpy_s((char*)arr, szData.GetLength()+1, szData.GetBuffer());
szData.ReleaseBuffer();
GlobalUnlock(h);
::OpenClipboard (NULL);
EmptyClipboard();
SetClipboardData(CF_TEXT, h);
CloseClipboard();
}

Related

Working with Bitmaps in WxWidgets

I have the following code given in the book "Cross-Platform GUI Programming with wxWidgets" which I'm reading:
BEGIN_EVENT_TABLE(MyWindow, wxWindow)
EVT_ERASE_BACKGROUND(MyWindow::OnErase)
END_EVENT_TABLE()
void MyWindow::OnErase(wxEraseEvent& event)
{
wxClientDC* clientDC = NULL;
if (!event.GetDC())
clientDC = new wxClientDC(this);
wxDC* dc = clientDC ? clientDC : event.GetDC() ;
wxSize sz = GetClientSize();
wxEffects effects;
effects.TileBitmap(wxRect(0, 0, sz.x, sz.y), *dc, m_bitmap);
if (clientDC)
delete clientDC;
}
This code doesn't show how do I load a bitmap so after some searching on google I came up with:
wxBitmap m_bitmap;
bool result = m_bitmap.LoadFile("D:\image.png", wxBITMAP_TYPE_PNG);
But this returns a boolean result of false which means the function LoadFile was failed to load the file. I have also tried to load a BMP file which fails too.
One another problem I'm having is that wxEffects is flagged deprecated by the complier warning.
You need to register the PNG image handler to be able to load PNG bitmaps. The simplest way to do is to call wxInitAllImageHandlers() function at some point during your application initialization, e.g. in your overridden MyApp::OnInit().
As for wxEffects being deprecated, this is just because the book is rather old and quite a few things have changed since then. I strongly recommend you to read the overview of important changes if you are using wxWidgets 3.0. And if you don't, I recommend you even stronger to use it.

Windows Forms - picture box. How to delete an Image

I am working in an application where there is a conbobox and a picturebox. The user selects a path and the conbobox loads paths to 2000 images, and displays the first one. When the user changes the index of the conbobox the image displayed changes, but I don't know how to delete the image in the picturebox.
If I just overwrite the image it doesnt do the job, as when I do it repeatedly the program crashes because of memory. How do I delete a image Inside the picturebox?
EDIT:
I made few changes and can't seem to reproduce the error again.. so maybe it was something else. but just for checking, is this code leaking memory?
tips: config is a singleton containing where some info, in this case, where the images are.
private: System::Void comboBox_image1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
System::String^ aux;
DIC_config* config=DIC_config::Instance();
if(config->images_path!=NULL){
aux=gcnew System::String(config->images_path);
aux=aux+"\\CAM_0\\Snap_0_0"+(this->comboBox_image1->SelectedIndex+1)+".bmp";
System::IO::FileStream^ image_file=gcnew System::IO::FileStream(aux,System::IO::FileMode::Open,System::IO::FileAccess::Read);
System::Drawing::Bitmap^ img = gcnew System::Drawing::Bitmap(image_file);
this->pictureBox_image1->Image=img;
//img->~Bitmap(); this doesnt work, deletes the image of picturebox and makes the program chrash
}
}
You have to dispose the old image. Forgetting to do so makes it likely your program runs out of unmanaged memory when the garbage collector doesn't run frequently enough. Bitmap objects are quite small, you can allocate thousands of them without ever triggering a GC, but can consume a lot of unmanaged memory for the pixel data. You dispose objects in C++/CLI with the delete operator, it calls IDisposable::Dispose().
Do note that the FileStream you use is also a disposable object. Doing it this way requires you to keep the stream opened while the bitmap is in use and close it afterwards. You correctly did not dispose the stream but forgot closing it. Too hard to get right, it is much easier to use the Bitmap constructor that accepts a string for the file path so the Bitmap class manages the underlying stream itself. Fix:
aux = config->images_path;
aux += ....;
System::Drawing::Bitmap^ img = gcnew System::Drawing::Bitmap(aux);
delete this->pictureBox_image1->Image;
this->pictureBox_image1->Image = img;
This doesn't work because you are trying to call destructor of the class, not the instance. Furthermore you do not need to call it as System::Drawing::Bitmap is under control of garbage collector, so the finalizer ( !Bitmap() ) will be called automatically if it's not referenced any longer.
What you can do if you want to close it in picturebox is
delete this->pictureBox_image1->Image;
image_file->Close(); //after closing/deleting the open bitmap
btw. your code is not pure c++, but c++/cli, so I've added the tag
First set a null pointer to the Image property and refresh the pictureBox, as given below,
pictureBox_image1->Image = nullptr;
pictureBox_image1->Refresh();

How to set the text in a TextBox control from native code?

Is it possible to manipulate .net controls from native code? Particularly, I'd like to set the text of a TextBox from some native code. I want it done this way to keep the business logic separated from the user interface, but it is precisely the native code which only knows how to appropriately format the data (some bytes received within a protocol).
I know I could get the window handle through the Handle property, but once there, how would I call the desired method?
Is string handling my only option? Should the native code build up the message to be displayed on the control?
The "native" way of setting the text on a textbox is to send the textbox the WM_SETTEXT message:
// handle is initialized from TextBox::Handle
PostMessage(handle, WM_SETTEXT, 0, _T("Some text"));
Read up on PostMessage and SendMessage, too. Depending on how you allocate and build up the text, you may need to use SendMessage to avoid deallocating prematurely.
If you want to keep your business logic separated from your user interface, and some of your business logic is in native code, then it would be a really good idea not to change any GUI content from the native code directly, because it is exactly the opposite of what you want to achieve. Better try to write some kind of wrapper method in C++/CLI to call the native data format routine from there, making it available for your use in your GUI code.
If you really want to make calls from native code to managed code, you can declare a (native!) static method in C++/CLI which calls a managed method. You can pass a function pointer to such a method to a lower layer of your program (for example, your native C++ layer), which can be called from there.
Something along the lines of:
// the native code layer:
// "Callbacks.h"
void (*_myNativeCallback)();
void InitCallback(void (*myNativeCallback)())
{
_myNativeCallback=myNativeCallback;
}
// now you can use _myNativeCallback within your native code
// the C++/CLI layer:
#include "Callbacks.h"
//...
static void MyNativeCallback()
{
ManagedClass::StaticMethod();
}
InitCallback(MyNativeCallback);
In ManagedClass::StaticMethod, you have access to your .NET code and you should not have any problems to manipulate a TextBox of any form you can reach from there. If you have to convert a native string to a System::String, you may find this code snippet helpful:
inline System::String StdToSysString(const std::string &s)
{
return gcnew System::String(s.c_str());
}
And the other way round (Ansi code page assumed):
inline std::string SystemToStdString(System::String ss)
{
using namespace System::Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(ss)).ToPointer();
std::string s = chars;
Marshal::FreeHGlobal(System::IntPtr((void*)chars));
return s;
}

Hardcoding the resources in application

I have some code which shows a simple dialog box and handles user action (written using plain WinAPI).
// Display dialog and handle user action
LRESULT choice = DialogBoxParam(NULL, MAKEINTRESOURCE(AP_IDD_DIALOG), NULL, (DLGPROC)DialogCallback, NULL);
Is there any way to hardcode the resource file dialog.rc, which is used to build the dialog ?(I would like to get rid of .rc files and I'm pretty sure there is a way, yet I don't know what it is :)
Edit
Also, does someone have any ideas on converting existing .rc files into hardcoded resources? Is this possible?
*.rc (resource) files are source code, they are compiled with the resource compiler and linked into your object (.exe/.dll)
You don't need to ship the resource file or have it present with your app to run it.
If you want to move to programmatically defined windows rather than templates then you might want to be looking at QT/wxWidgets. But thats a fair chunk of overhead for 1 dialog!
I'm surprised I couldn't find an existing app to do this sort of thing, enough hits on google with people trying to do this.
Ok, so the DLGTEMPLATE is a variable length blob of data, normally you let the dialog function pull it from the resource bundle for you, but instead you want to store it in your program.
You need to change your static lib to have a new function to decode some 'blob' back into the dlgtemplate, and you need to generate the blob. (or add the blob in your code without decoding which I don't want to think about right now)
The following code will give you the DLGTemplate data you need to imbed in your app. (cut from larger project)
HGLOBAL LoadResourceImpl(wchar_t *resource, wchar_t *type)
{
HRSRC handle = FindResource(hInstance, resource,type);
if (handle)
{
HGLOBAL hResource = LoadResource(hInstance, handle);
if (hResource)
return LockResource(hResource);
}
return 0;
}
DLGTEMPLATE * LoadDialog(wchar_t *resource)
{
return (DLGTEMPLATE *) LoadResourceImpl(resource,RT_DIALOG);
}
DLGTEMPLATE * LoadDialog(int resource)
{
return (DLGTEMPLATE *) LoadResourceImpl(MAKEINTRESOURCE(resource),RT_DIALOG);
}
Make an app that includes your resource - use the appropriate LoadDialog to get the data.
Now "write out" that blob in a format to include in your app -
step 1 - find out how much data there is by traversing the structure to find the total size including all the controls (control count is in DLGTEMPLATE::cdit)
step 2 - convert the data to something you can compile into your code - like HEX
Add to your static library a new 'HEX' to DLGTEMPLATE method and the hex string you made using the other app.
Can we hard code the .res file into the program?
the resource compiler converts .rc into .res
use a hex dump tool (eg. winhex) to translate the .res into bytes array
(represented in C source code).
add the source code file in the project and compile in the executable.
locate the dialog resource position from the array and use DialogBoxIndirect.
DialogBoxParamIndirect can be used instead. It takes as a parameter the dialog template. Raymond Chen's blog has an example of building a dialog box at runtime rather than from a resource using the DialogBox*Indirect API's.
Per MSDN, dialog box resources are basically composed of the DLGTEMPLATE and DLGITEMTEMPLATE structures. So you should be able to use the resource API's (FindResource, LoadResource, and LockResource) to get at the underlying bits of an existing dialog resource, and embed that within your code.
Note that this is a lot more painful than using the .rc file. It's much more difficult to make changes to your layout, and it's also much less localizable, since localization would now require a code change to update the template in code.
If it's a simple dialog, why use the DLGTEMPLATE at all?
Nothing stops you from simply doing ::CreateWindow'ing those controls directly. If it's a simple dialog with 2-3 buttons and a couple text fields, simply call ::CreateWindow, passing in the window class of whatever common control you're using.
This is essentially what the DialogXxxxx functions do anyway. DLGTEMPLATE is a convenience for declaratively laying out your forms, and having the boilerplate make the appropriate CreateWindow calls, etc.

visual c++ copy textbox content

how to copy textbox->Text content in a char array?
i m working in vc++.
Use CWnd::GetWindowText()
CString str;
CWnd* pWnd = GetDlgItem(IDC_WHATEVER);
pWnd->GetWindowText(str);
Puts the contents of the control into the CString or you can use the array version:
TCHAR sz[10];
int nRet = pWnd->GetWindowText(sz, 10);
Your query is unclear, so I'll have to assume things.
Assuming you are using MFC, add a control type variable to your edit box (say m_Edit), and use m_Edit.GetWindowText() to get the text.
Or if you're using plain Win32, use the GetWindowText() Win32 API.
On an additional note, like another user pointed out, stop using things like fixed-size character arrays to store strings if you are using c++. Use something like std::string or use CString if you're using MFC. By doing so, you can manipulate strings much easily and your code will be less error prone.
Cheers, Rajesh. MVP, Visual C++
You can also try like this.....
CString csTbxName;
GetDlgItemText(IDC_EDIT1,csTbxName);
const char* pchTbxName = csTbxName.GetBuffer();
char chTbxNameDup[5000];
ZeroMemory(chTbxNameDup,5000);
if(csTbxName.GetLength() < 5000)
{
memcpy(chTbxNameDup,(void*)pchTbxName,csTbxName.GetLength());
}