Load icon from .DLL in wxWidgets - c++

I am attempting to load a wxIcon in Windows by loading from a system DLL (as the mime system told me that the icon for such a file type was in the DLL), eg.
wxIcon icon;
icon.LoadFile("C:\\WINDOWS\\system32\\zipfldr.dll", wxICON_DEFAULT_TYPE);
This fails but I was wondering if there was any way in the codebase of loading this, other than resorting to native Win32 functions.
Also, if there are native Win32 functions, does anyone know what they are?
EDIT: I have tried the following with no success:
::wxInitAllImageHandlers();
wxMimeTypesManager manager;
wxFileType* type = manager.GetFileTypeFromExtension("sys");
wxIconLocation location;
if (type->GetIcon(&location))
{
// location is something like C:\WINDOWS\system32\imageres.dll
wxIcon icon;
if (!icon.LoadFile(location.GetFileName(), wxBITMAP_TYPE_ICON /*I have tried wxICON_DEFAULT_TYPE too*/))
{
// Failed!
}
}
EDIT 2: In response to VZ, I have tried the following with no success sadly:
::wxInitAllImageHandlers();
wxMimeTypesManager manager;
wxFileType* type = manager.GetFileTypeFromExtension("sys");
wxIconLocation location;
if (type->GetIcon(&location))
{
// location is something like C:\WINDOWS\system32\imageres.dll,
//with an appropriate index as retrieved by location.GetIndex(), which is -67.
wxIcon icon(location);
if (!icon.IsOk())
{
BREAK;
// Failed!
}
}
EDIT 3:
Thanks for everyone's help - works fine if I use wxBITMAP_TYPE_ICO instead of wxBITMAP_TYPE_ICON (notice the N), and also I was putting my test code in my app's constructor instead of in ::OnInit. It worked in OnInit but not in the constructor so that's a lesson learned!
Thanks everyone for the help and speedy responses, much appreciated as always.

It should work if you specify type wxBITMAP_TYPE_ICO.

The first argument to LoadFile() must specify the icon resource ID when using wxBITMAP_TYPE_ICO (which is indeed what you need to use when loading icons from files, and not resources of the current module), i.e. you're also missing the ;N part at the end, where N is the value returned by wxFileTypeInfo::GetIconIndex().
But to avoid dealing with this explicitly, you should just use wxFileType::GetIcon() and construct wxIcon from the wxIconLocation filled in by it.
For example, this:
diff --git a/samples/minimal/minimal.cpp b/samples/minimal/minimal.cpp
index 0d91f7fc75..3623aacc56 100644
--- a/samples/minimal/minimal.cpp
+++ b/samples/minimal/minimal.cpp
## -123,6 +123,12 ## bool MyApp::OnInit()
if ( !wxApp::OnInit() )
return false;
+ wxIcon icon(wxIconLocation(R"(c:\Windows\system32\imageres.dll)", -67));
+ if ( icon.IsOk() )
+ {
+ wxLogMessage("Loaded icon of size %d*%d", icon.GetWidth(), icon.GetHeight());
+ }
+
// create the main application window
MyFrame *frame = new MyFrame("Minimal wxWidgets App");
shows the expected message about loading the icon of size 32 by 32.

Related

Parsing yaml files with yaml-cpp

I'm having problem with parsing yaml files using yaml-cpp, I'm making a application using wxWidgets and I'm trying to read the frame size from a yaml file which looks like,
---
This is the configuration file for the Sample Browser,
feel free to edit this file as needed
...
Window:
SizeW: 1280
SizeH: 720
Media:
Autoplay: false
And this the code that should handle the parsing,
int sizeH, sizeW;
try
{
YAML::Node config = YAML::LoadFile("/home/apoorv/repos/cpp-projects/wxWidgets/SampleBrowser/build/config.yaml");
if (!config["Window"])
{
wxLogDebug("Error! Cannot fetch values.");
}
sizeH = config["SizeH"].as<int>();
sizeW = config["SizeW"].as<int>();
}
catch(const YAML::ParserException& ex)
{
std::cout << ex.what() << std::endl;
}
this->SetSize(sizeW, sizeH);
But when I try to parse this file and set the frame size this->SetSize() it errors out saying *** Caught unhandled unknown exception; terminating.
Since SizeH and SizeW are children of Window, your two lines should look like
sizeH = config["Window"]["SizeH"].as<int>();
sizeW = config["Window"]["SizeW"].as<int>();
or, merged with the previous check,
if (auto window = config["Window"]) {
sizeH = window["SizeH"].as<int>();
sizeW = window["SizeW"].as<int>();
} else {
wxLogDebug("Error! Cannot fetch values.");
}
Generally, the error handling is bad. In your code, if an error is encountered, sizeH and sizeW are not set but are still given to SetSize. This is undefined behavior. You should initialize them with some default values, e.g.
int sizeH = 480, sizeW = 640;
Also, since you keep us in the dark about what this is, there may be other errors.
It's fine to try to do this for learning yaml-cpp, but if you really want to save/restore your frame geometry, you should use wxPersistentTLW instead. To use it, just call wxPersistentRegisterAndRestore(frame, "NameToIdentifyYourFrame") after creating your frame, see the manual for more details.
In the cross-platform environment it is better to save the client size of the window, as for GTK what's important is the client size. There might be other OSes/toolkits where this is the case.

Window placement issue - what is re-positioning my window?

I have a C++ / MFC app and I trying to save and restore the window placement of my CFrameWnd derived main frame. I have my GetWindowPlacement and SetWindowPlacement calls in the appropriate places, and all seems to be working well.
That is until I 'store' the window when it is maximised. In that case, when I re-open the app and use the debugger to step over my SetWindowPlacement call, I see that it is placed maximised, as I wanted.
But then if I continue execution, something else 'restores' my window to it's non-maximised size. How do I discover what is doing that? (Since I'm not calling ShowWindow anywhere else)
EDIT: It seems to stem from CFrameWnd::InitialUpdateFrame:
int nCmdShow = -1; // default
CWinApp* pApp = AfxGetApp();
if (pApp != NULL && pApp->m_pMainWnd == this)
{
nCmdShow = pApp->m_nCmdShow; // use the parameter from WinMain
pApp->m_nCmdShow = -1; // set to default after first time
}
ActivateFrame(nCmdShow);
If I set my app m_nCmdShow to SW_MAXIMIZED on start up, it shows maxed - but it's always maxed! I have my SetWindowPlacement in my CMainFrame::OnActivate - should it be somewhere else?
So In my App start up I did this:
WINDOWPLACEMENT* lwp;
UINT nl;
if (AfxGetApp()->GetProfileBinary(_T("MainFrame"), _T("WP"), (LPBYTE*)&lwp, &nl))
{
m_nCmdShow = lwp->showCmd;
}
delete [] lwp;
It seems to work

VS 2005 C++ edit content of the CRichEditCtrl instance

I've installed a Windows XP Professional SP3 on a VMWare image and the Visual Studio 2005 on it. I've created a new dialog based C++ MFC project with /clr support. I've put a RichEdit 2.0 control onto the auto-generated dialog and I'm trying to read up a text file and put its content into this RichEdit 2.0 control by button click without formatting. I've added a variable to the RichEdit 2.0 called pCRichEditCtrl and here is my code which doesn't work.
CWinApp inheritance:
BOOL CTextFormatterApp::InitInstance()
{
...
AfxInitRichEdit2();
CWinApp::InitInstance();
...
}
CDialog inheritance:
void CTextFormatterDlg::OnBnClickedButton1()
{
StreamReader^ objReader = gcnew StreamReader("c:\\text.txt");
String ^sLine = "";
sLine = objReader->ReadLine();
while (sLine != nullptr)
{
pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(CString(sLine));
sLine = objReader->ReadLine();
}
objReader->Close();
}
I don't know whether it counts but I get the following warnings at linking:
TextFormatterDlg.obj : warning LNK4248: unresolved typeref token (01000016) for 'AFX_CMDHANDLERINFO'; image may not run
TextFormatter.obj : warning LNK4248: unresolved typeref token (01000012) for 'AFX_CMDHANDLERINFO'; image may not run
TextFormatterDlg.obj : warning LNK4248: unresolved typeref token (01000015) for 'IAccessibleProxy'; image may not run
I'm not sure what I'm doing because I'm familiar only with newer frameworks and I don't know either Windows.
Input file exists, I can see the read text if I debug the application but I can't see any changes in the edit box. I've tried to call pCRichEditCtrl.UpdateData(true); but nothing has changed.
Is it enough to add a variable for getting the controller of the box (pCRichEditCtrl)? It seems to the pointer doesn't point to the proper control item.
Do you have any idea what is missing?
There's no need to use CLI to just read text files, try something like:
void CTextFormatterDlg::OnBnClickedButton1()
{ CStdioFile f1;
CString sLine;
if (!f1.Open(_T("c:\\text.txt"), CFile::modeRead | CFile::typeText))
return;
while (f1.ReadString(sLine))
{ pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(sLine);
}
f1.Close();
}
EDIT: control variable pCRichEditCtrl
a) should be declared in the dialog class as CRichEditCtrl pCRichEditCtrl;
b) should be connected to the ID of the control (e.g.: IDC_RICHEDIT21), like
void CTextFormatterDlg::DoDataExchange(CDataExchange* pDX)
{ CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_RICHEDIT21, pCRichEditCtrl);
}
c) I have tested the following code and it works for me (adds "aa" to the control window on each button click)
pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(TEXT("aa"));
I share the final solution with the community to be available for those who faces with the same issue. I don't know why do I have to use Update(FALSE); on the CWinApp inheritance two times but it solves everything. If someone has an idea or a better (nicer) solution don't hesitate to share it with us, I'll move the accepted flag to that version (if it is possible, I haven't tried it before).
void CTextFormatterDlg::OnBnClickedButton1()
{
StreamReader^ objReader = gcnew StreamReader("c:\\text.txt");
String ^sLine = objReader->ReadLine();
UpdateData(FALSE); //this is the first unexpected first aid
while (sLine != nullptr)
{
pCRichEditCtrl.SetSel(pCRichEditCtrl.GetTextLength(), -1);
pCRichEditCtrl.ReplaceSel(CString(sLine + "\r\n"));
UpdateData(FALSE); //this is the second unexpected first aid
sLine = objReader->ReadLine();
}
objReader->Close();
}

Windows phone 8 on emulator - why can't I play audio files?

I'm converting an app that was written in Silverlight, and so far I've succeeded in solving all of the problems, except for one:
For some reason, the emulator refuses to play any audio files of the app, and it doesn't even throw an exception. I've checked, and in the ringtone category it can make sounds.
The original code was :
<Grid x:Name="sharedFullScreenFilePathContainer"
Tag="{Binding StringFormat=\{0\},Converter={StaticResource fullScreenImageConverter}}">
<Image x:Name="fullScreenImage" Stretch="Fill"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/images/\{0\}.jpg}"
ImageFailed="onFullScreenImageFailedToLoad" MouseLeftButtonDown="onPressedOnFullScreenImage" />
<MediaElement x:Name="mediaPlayer" AutoPlay="True"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/sounds/\{0\}.wma}" />
</Grid>
so, the image that I set to this item's context is really shown, but the sound that really exists on the path I set to it doesn't play (I've checked in the "Bin" folder).
I've tried to use code instead of xaml, but I still have the same problem.
I've tried this (though it's usually used for background music):
AudioTrack audioTrack = new AudioTrack(new Uri("../Assets/sounds/" + fileToOpen, UriKind.Relative), "", "", "", null);
BackgroundAudioPlayer player = BackgroundAudioPlayer.Instance;
player.Track = audioTrack;
player.Play();
It didn't play anything, and also didn't throw any exception.
I've also tried the next code, but it throws an exception (file not found exception) probably because I don't call it right:
Stream stream = TitleContainer.OpenStream("#Assets/sounds/" + fileToOpen);
SoundEffect effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
I've also tried using wma files but it also didn't work.
I also tried to play with the "copy to output directory" parameter of the mp3 files (to "always" and "only if new" ) and with the "build action" parameter (to "none" and "content" ). Nothing helps.
Can anyone please help me? I didn't develop for Silverlight/WP for a very long time and I can't find out how to fix it .
Btw, since later I need to know when the sound has finished playing (and also to be able to stop it), I would like to use code anyway. I would be happy if you could also tell me how to do it too (I can ask it on a new post if needed).
EDIT:
ok , i've found out the problem : i kept getting a weird exception when using the MediaPlayer.Play() method , and after checking out about the exception , i've found out that it's a known issue , and that i need to call FrameworkDispatcher.Update(); right before i call the Play() method .
so the solution would be to do something like this:
Song song = Song.FromUri(...);
MediaPlayer.Stop();
FrameworkDispatcher.Update();
MediaPlayer.Play(song);
the exception is:
'System.InvalidOperationException' occurred in System.Windows.ni.dll"
i've found the solution here .
Now the question is why , and how come I didn't find anything related to it in the demos of windows phone ? Also , i would like to know what this function does .
ok , since nobody gave me an answer to both questions , and I still wish to give the bounty , I will ask another question :
If there is really no solution other than using the MediaPlayer class for windows phone , how do i capture the event of finishing playing an audio file ? Even getting the audio file duration doesn't work (keeps returning 0 length , no matter which class i've tried to use) ...
The BackgroundAudioPlayer can play files only from isolated storage or from a remote URI, that is why you can here anything!
If you have your file as resources in your app, you must first copy them to the isolated store, and then make a reference to the file in the isolated store to your BackgroundAudioPlayer.
private void CopyToIsolatedStorage()
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = new string[]
{ "Kalimba.mp3",
"Maid with the Flaxen Hair.mp3",
"Sleep Away.mp3" };
foreach (var _fileName in files)
{
if (!storage.FileExists(_fileName))
{
string _filePath = "Audio/" + _fileName;
StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));
using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
{
int chunkSize = 4096;
byte[] bytes = new byte[chunkSize];
int byteCount;
while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
{
file.Write(bytes, 0, byteCount);
}
}
}
}
}
}
And then you can make a list of your songs
private static List<AudioTrack> _playList = new List<AudioTrack>
{
new AudioTrack(new Uri("Kalimba.mp3", UriKind.Relative),
"Kalimba",
"Mr. Scruff",
"Ninja Tuna",
null),
new AudioTrack(new Uri("Maid with the Flaxen Hair.mp3", UriKind.Relative),
"Maid with the Flaxen Hair",
"Richard Stoltzman",
"Fine Music, Vol. 1",
null),
new AudioTrack(new Uri("Sleep Away.mp3", UriKind.Relative),
"Sleep Away",
"Bob Acri",
"Bob Acri",
null),
// A remote URI
new AudioTrack(new Uri("http://traffic.libsyn.com/wpradio/WPRadio_29.mp3", UriKind.Absolute),
"Episode 29",
"Windows Phone Radio",
"Windows Phone Radio Podcast",
null)
};
And play your tracks!
private void PlayNextTrack(BackgroundAudioPlayer player)
{
if (++currentTrackNumber >= _playList.Count)
{
currentTrackNumber = 0;
}
PlayTrack(player);
}
private void PlayPreviousTrack(BackgroundAudioPlayer player)
{
if (--currentTrackNumber < 0)
{
currentTrackNumber = _playList.Count - 1;
}
PlayTrack(player);
}
private void PlayTrack(BackgroundAudioPlayer player)
{
// Sets the track to play. When the TrackReady state is received,
// playback begins from the OnPlayStateChanged handler.
player.Track = _playList[currentTrackNumber];
}
If you want the MediaElement to work from your code you can do something like this!
MediaElement me = new MediaElement();
// Must add the MediaElement to some UI container on
// your page or some UI-control, otherwise it will not play!
this.LayoutRoot.Children.Add(me);
me.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
me.Play();
Use the MediaElement instead, this can play media files stored in your application, but stops playing when the application stops (you can make some advance chance to your app so it keep running, but it will not work very well)
In your XAML:
<Button x:Name="PlayFile"
Click="PlayFile_Click_1"
Content="Play mp3" />
In your Code behind:
MediaElement MyMedia = new MediaElement();
// Constructor
public MainPage()
{
InitializeComponent();
this.LayoutRoot.Children.Add(MyMedia);
MyMedia.CurrentStateChanged += MyMedia_CurrentStateChanged;
MyMedia.MediaEnded += MyMedia_MediaEnded;
}
void MyMedia_MediaEnded(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Ended event " + MyMedia.CurrentState.ToString());
// Set the source to null, force a Close event in current state
MyMedia.Source = null;
}
void MyMedia_CurrentStateChanged(object sender, RoutedEventArgs e)
{
switch (MyMedia.CurrentState)
{
case System.Windows.Media.MediaElementState.AcquiringLicense:
break;
case System.Windows.Media.MediaElementState.Buffering:
break;
case System.Windows.Media.MediaElementState.Closed:
break;
case System.Windows.Media.MediaElementState.Individualizing:
break;
case System.Windows.Media.MediaElementState.Opening:
break;
case System.Windows.Media.MediaElementState.Paused:
break;
case System.Windows.Media.MediaElementState.Playing:
break;
case System.Windows.Media.MediaElementState.Stopped:
break;
default:
break;
}
System.Diagnostics.Debug.WriteLine("CurrentState event " + MyMedia.CurrentState.ToString());
}
private void PlayFile_Click_1(object sender, RoutedEventArgs e)
{
// Play Awesome music file, stored as content in the Assets folder in your app
MyMedia.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
MyMedia.Play();
}
Audio track plays audio files stored in isolated storage or streamed over the internet.
Playing audio files stored within the application package works fine for me. I got files named like "Alarm01.wma" in project folder Resources\Alarms. I then play these sounds like this:
using Microsoft.Xna.Framework.Media;
...
Song s = Song.FromUri("alarm", new Uri(#"Resources/Alarms/Alarm01.wma", UriKind.Relative));
MediaPlayer.Play(s);
Also don't forget to reference Microsoft.Xna.Framework library.
I guess it should work fine for mp3 files and files stored in IsolatedStorage as well.

How does MFC's "Update Command UI" system work?

I'd like to know more about how this system works, specifically when and how the framework actually decides to update a UI element.
My application has a 'tools' system where a single tool can be active at a time. I used the "ON_UPDATE_COMMAND_UI" message to 'check' the tool's icon/button in the UI, which affected both the application menu and the toolbars. Anyway, this was all working great until some point in the last couple of days, when the toolbar icons stopped getting highlighted properly.
I investigated a little and found that the update command was only being received when the icon was actually clicked. What's strange is this is only affecting the toolbars, not the menu, which is still working fine. Even when the buttons in the menu are updated the toolbar icon stays the same.
Obviously I've done something to break it - any ideas?
EDIT:
Never mind. I'd overwritten the Application's OnIdle() method and hadn't called the original base class method - that is, CWinApp::OnIdle() - which I guess is where the update gets called most of the time. This code snippet from https://msdn.microsoft.com/en-us/library/3e077sxt.aspx illustrates:
BOOL CMyApp::OnIdle(LONG lCount)
{
// CWinApp's original method is involved in the update message handling!
// Removing this call will break things
BOOL bMore = CWinApp::OnIdle(lCount);
if (lCount == 0)
{
TRACE(_T("App idle for short period of time\n"));
bMore = TRUE;
}
// ... do work
return bMore;
// return TRUE as long as there are any more idle tasks
}
Here's a good article that kinda explains how to do it. Don't use his code example with WM_KICKIDLE though, instead scroll down to the comments section. There are two code samples that explain how to do it better. I quote:
//Override WM_INITMENUPOPUP
void CDialog::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
CDialog::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
// TODO: Add your message handler code here
if(pPopupMenu &&
!bSysMenu)
{
CCmdUI CmdUI;
CmdUI.m_nIndexMax = pPopupMenu->GetMenuItemCount();
for(UINT i = 0; i < CmdUI.m_nIndexMax; i++)
{
CmdUI.m_nIndex = i;
CmdUI.m_nID = pPopupMenu->GetMenuItemID(i);
CmdUI.m_pMenu = pPopupMenu;
// There are two options:
// Option 1. All handlers are in dialog
CmdUI.DoUpdate(this, FALSE);
// Option 2. There are handlers in dialog and controls
/*
CmdUI.DoUpdate( this, FALSE );
// If dialog handler doesn't change state route update
// request to child controls. The last DoUpdate will
// disable menu item with no handler
if( FALSE == CmdUI.m_bEnableChanged )
CmdUI.DoUpdate( m_pControl_1, FALSE );
...
if( FALSE == CmdUI.m_bEnableChanged )
CmdUI.DoUpdate( m_pControl_Last, TRUE );
*/
}
}
}
See if this helps - http://msdn.microsoft.com/en-us/library/essk9ab2(v=vs.80).aspx