Changing the Total Number of Recent Files - c++

I'd like the user to be able to edit the number of recent files shown in the File menu of my MFC application. I've used two very good references:
http://www.codeproject.com/KB/menus/changemru.aspx
http://www.microsoft.com/msj/0899/c/c0899.aspx
It involves deleting and recreating the CRecentFileList object stored in CWinApp::m_pRecentFileList. Unfortunately, I find that the menu is not updated properly after replacing the CRecentFileList. See code snippet below:
void CMyWinApp::SetMRUListSize( int size )
{
// size guaranteed to be between 1 and 16
delete m_pRecentFileList ;
LoadStdProfileSettings( size ) ;
}
What can I do to ensure that what is drawn into the File menu is synchronized with m_pRecentFileList after I recreate the object?

My CApp derives from CWinApp. In initInstance, you have this line:
LoadStdProfileSettings(10);
At the end of InitInstance, add this code:
m_pmf->m_pRecentFileList = m_pRecentFileList;
Here m_pmf is my MainFrame class and I created a member CMainFrame::m_pRecentFileList of type CRecentFileList which is in the MFC source file filelist.cpp. m_pRecentFileList on the right is protected and CMainFrame doesn't have access to it from outside InitInstance, but you can make a functional copy here.
At the end of CMainFrame::OnClose, force a registry update by:
m_pRecentFileList->WriteList();
// Force registry update on exit. This doesn't work without forcing.
I don't even have to rebuild m_pRecentFileList, the MRU mechanism updates it correctly. Example: 5 MRU items, the first is moved to another directory and can no longer be found. Stepping through the code in the debugger shows that the bad entry is removed from the list. For some reason, the updated list isn't saved correctly unless I force it as explained above. I originally thought the problem might have something to do with privileges (64-bit Win7), but running the app as admin didn't help.

Some of Microsoft's documentation suggest you should call CWinApp::LoadStdProfileSettings from within InitInstance. This suggests to me that it's something done once during initialisation rather than at run time.
Have you tried fully implementing the second of the two links you provided? My guess is you need to add the second part instead of the call to CWinApp::LoadStdProfileSettings:
m_pRecentFileList = new CRecentFileList(0, strSection, strEntryFormat, nCount);
if(m_pRecentFileList)
{
bReturn = TRUE;
// Reload list of MRU files from registry
m_pRecentFileList->ReadList();
}
[Edit] Apparently m_pRecentFileList points to an CRecentFileList Class . Have you tried calling CRecentFileList::UpdateMenu?
There's another CodeProject example which might help too.

Related

How to modify and update Visual Studio Object

I want to delete all the object that is not used now.
I used Visual Studio 2019.
When I search Object Browser, It gets to me some strange struct or class that I modified of name.
For example, first I define a structure as
typedef struct stOutput
{
double dDirtyPrice_CumInt;
double dDM;
//...
double dYield;
} stOutput
Later I changed this definition to
typedef struct stOutput_New
{
double dAI;
//...
long lObservStartDate;
} stOutput_New
However, the object browser shows to me just
stOutput.
There is no stOutput_New.
Also I put my cursor on 'stOutput_New' and push 'F12' then it locates my view some strange area.
There are even no 'stOutput_New'
Now, below picture is describing my real situation
This is 'Class View'
Actually I just use One stOutput, but there are so many stOutput that has same file path
Also below picture is my 'Object Browser'
As you can see the two stOutput have different member variables.
And I changed the name from stOutput to stOutput_new the latter.
But it seems my object browser didn't reflect it.
I tried
Project Unload and Reload it
Organize the code of Solution and Project
Re-Build Solution.
But everything doesn't work.
Please help me
In vs2019, I defined the structure exactly like yours according to your description, and then changed the structure according to your description. My object browser did not have the problem you described. If you are sure that your code does not repeat the definition of structure and other problems, I suggest you reinstall or repair VS.
enter image description here

MFC SetRegistryKey opposite function? What am I missing?

In my app the default Registry key is created called:
SetRegistryKey(_T("Trains"));
It places that "root" key value like so:
Computer\HKEY_CURRENT_USER\SOFTWARE\Trains
My app saves all the window info and other data in subkeys under Trains. I have a "reset" menu item that when the user activates, I would like to delete that "root" key and all the subkeys under it.
If I'm in registry editor, it is simply a right click and delete....and blamo, all gone.
I've read other threads here and on Google and there seems to be multiple ways to do this.... I've tried DelRegTree with little success and I'm unclear why this process is so cumbersome to do with multiple functions and recursion to find all the keys, delete them, then remove the root key.
https://learn.microsoft.com/en-us/cpp/mfc/reference/cwinapp-class?view=msvc-160#delregtree
I've tried DelRegTree(\\HKEY_CURRENT_USER\\SOFTWARE, _T("Trains")); but that doesn't work. How should I approach this seemingly easy task?
You can use the SHDeleteKey() function. You can use HKEY_CURRENT_USER for the first argument and specify the key path (from that) in the second:
#include <shlwapi.h>
LSTATUS status = SHDeleteKey(HKEY_CURRENT_USER, _T("SOFTWARE\\Trains"));
You will need to include "Shwlapi.lib" in your link.
(Note: Calling the DelRegTree member of CWinApp may also work, if you use the same arguments; but you can't add the \\SOFTWARE part to the first argument – that will have to be included in the key path/name.)

Initialization of wxColourDataBase while creating a new wxColourPickerCtrl

This is my first question ever posted, so please let me know if there is anything that needs changes in my post :)
I am currently working on a dialog that is supposed to let the user change the background-color for some signal plotting. The "wxColourPickerCtrl" seems to do exactly what I need. Since there are multiple plots/pictures to be manipulated, the ColourPickerCtrls are initialized in a loop with the chosen background color as the default value:
for (const auto& [signalName, signalProperties] : properties)
{
wxColourPickerCtrl* selectBackgroundColor = new wxColourPickerCtrl(this, signalProperties.first, signalProperties.second.backgroundColor, wxDefaultPosition, wxDefaultSize);
}
"this" is an object of type SignalPropertiesDialog, which is directly inherited from wxDialog.
I have left out all the necessary sizer stuff, since it's not relevant for the problem (at least imo). "properties" is structured as follows:
std::map<std::string, std::pair<int, GraphPicture::Properties>> signalProperties_;
where GraphPicture::Properties contains the properties I want to manipulate:
struct Properties
{
wxColour backgroundColor{ *wxWHITE };
wxColour lineColor{ *wxBLACK };
int linewidth_px{ 1 };
bool isShown{ true };
};
The application successfully builds but immediately crashes on startup while generating those color picker objects.
wxIshiko has uploaded multiple tutorials and code snippets as examples for various wxWidgets controls, including the wxColourPickerCtrl. So I downloaded the sample code and tried to run it. Surprisingly, it worked.
While running through the code step by step I noticed the following difference:
The wxColourPickerCtrl is based on wxPickerBase. The wxPickerBase is created by calling the constructor of wxColourPickerCtrl (what I am actually doing in my code). During the construction of the wxPickerBase, the desired color is called by the name wxColourDataBase::FindName(const wxColour& color) const where the wxColourBase itself is instantiated. This is where the difference is:
When running the code snippet by wxIshiko, wxColourDataBase is instantiated correctly including the member m_map of type wxStringToColourHashMap* which is set to be NULL.
When running the code written by myself, wxColourDataBase is not correctly instantiated, and thus the member m_map is not set to be NULL, which leads to to the crash.
I have the feeling that there is nothing wrong with the way I set up the wxColourPickerCtrls. I somehow think there is a difference in the solution properties of the projects. I checked those but was not able to find any relevant differences.
I would really appreciate any hint or help since I am completely stuck on that problem.
Thank you very much in advance and have a good one,
Alex
EDIT:
I attached a screeny of the call stack.
Call stack
When does this code run exactly? If it is done after the library initialization (which would be the case, for example, for any code executed in your overridden wxApp::OnInit()), then wxTheColourDatabase really should be already initialized and what you observe should be impossible, i.e. if it happens it means that something is seriously wrong with your library build (e.g. it doesn't match the compiler options used when compiling your applications).
As always with such "impossible" bugs, starting with a known working code and doing bisection by copying parts of your code into the working version until it stops working will usually end up by finding a bug in your code.

Update an element that already has a plugin

Zurb Foundation 6.5.3
I have an accordion menu which needs to be updated via ajax after the initial page load. So initially the menu contains 2 items, then $(document).foundation(); is called. Later after an ajax response is received elements are added (and potentially removed/replaced) within the menu.
I would like to be able to re-use the same elements however, I can't update the plugin to re-style the changed elements. I've tried:
$("#my-menu").foundation(); which doesn't work and shows the error:
Tried to initialize accordion-menu on an element that already has a Foundation plugin.
Foundation.reflow(menu, 'accordion'); which doesn't work.
menu.foundation('reflow'); which doesn't work and shows the error:
Uncaught ReferenceError: We're sorry, 'reflow' is not an available method for AccordionMenu.
I have made it work by destroying and removing the existing menu, re-creating the whole thing, then calling $("#my-menu").foundation(); however this isn't ideal in my opinion.
I found that my issue was due to no one solution working in all 3 cases:
foundation has not yet been initialised
foundation is initialised and the entire element has been replaced since
foundation is initialised and the element has been updated since
Unless someone has a better answer, I solved using this approach:
// this can happen before, or after code creates the menu
$(document).foundation();
console.log("foundation run");
__foundationRun = true;
...
function foundationUpdate(el) {
if (__foundationRun) {
if (el.data('zfPlugin'))
// already initialised, update it
Foundation.reInit(el);
else
// new element, initialise it
el.foundation();
}
// else leave for foundation initialise
}
....
// ... do updates (modify or replace entirely) and then:
foundationUpdate($("#my-menu"));

c++ best way to realise global switches/flags to control program behaviour without tying the classes to a common point

Let me elaborate on the title:
I want to implement a system that would allow me to enable/disable/modify the general behavior of my program. Here are some examples:
I could switch off and on logging
I could change if my graphing program should use floating or pixel coordinates
I could change if my calculations should be based upon some method or some other method
I could enable/disable certain aspects like maybe a extension api
I could enable/disable some basic integrated profiler (if I had one)
These are some made-up examples.
Now I want to know what the most common solution for this sort of thing is.
I could imagine this working with some sort of singelton class that gets instanced globally or in some other globally available object. Another thing that would be possible would be just constexpr or other variables floating around in a namespace, again globally.
However doing something like that, globally, feels like bad practise.
second part of the question
This might sound like I cant decide what I want, but I want a way to modify all these switches/flags or whatever they are actually called in a single location, without tying any of my classes to it. I don't know if this is possible however.
Why don't I want to do that? Well I like to make my classes somewhat reusable and I don't like tying classes together, unless its required by the DRY principle and or inheritance. I basically couldn't get rid of the flags without modifying the possible hundreds of classes that used them.
What I have tried in the past
Having it all as compiler defines. This worked reasonably well, however I didnt like that I couldnt make it so if the flag file was gone there were some sort of default settings that would make the classes themselves still operational and changeable (through these default values)
Having it as a class and instancing it globally (system class). Worked ok, however I didnt like instancing anything globally. Also same problem as above
Instancing the system class locally and passing it to the classes on construction. This was kinda cool, since I could make multiple instruction sets. However at the same time that kinda ruined the point since it would lead to things that needed to have one flag set the same to have them set differently and therefore failing to properly work together. Also passing it on every construction was a pain.
A static class. This one worked ok for the longest time, however there is still the problem when there are missing dependencies.
Summary
Basically I am looking for a way to have a single "place" where I can mess with some values (bools, floats etc.) and that will change the behaviour of all classes using them for whatever, where said values either overwrite default values or get replaced by default values if said "place" isnt defined.
If a Singleton class does not work for you , maybe using a DI container may fit in your third approach? It may help with the construction and make the code more testable.
There are some DI frameworks for c++, like https://github.com/google/fruit/wiki or https://github.com/boost-experimental/di which you can use.
If you decide to use switch/flags, pay attention for "cyclometric complexity".
If you do not change the skeleton of your algorithm but only his behaviour according to the objets in parameter, have a look at "template design pattern". This method allow you to define a generic algorithm and specify particular step for a particular situation.
Here's an approach I found useful; I don't know if it's what you're looking for, but maybe it will give you some ideas.
First, I created a BehaviorFlags.h file that declares the following function:
// Returns true iff the given feature/behavior flag was specified for us to use
bool IsBehaviorFlagEnabled(const char * flagName);
The idea being that any code in any of your classes could call this function to find out if a particular behavior should be enabled or not. For example, you might put this code at the top of your ExtensionsAPI.cpp file:
#include "BehaviorFlags.h"
static const enableExtensionAPI = IsBehaviorFlagEnabled("enable_extensions_api");
[...]
void DoTheExtensionsAPIStuff()
{
if (enableExtensionsAPI == false) return;
[... otherwise do the extensions API stuff ...]
}
Note that the IsBehaviorFlagEnabled() call is only executed once at program startup, for best run-time efficiency; but you also have the option of calling IsBehaviorFlagEnabled() on every call to DoTheExtensionsAPIStuff(), if run-time efficiency is less important that being able to change your program's behavior without having to restart your program.
As far as how the IsBehaviorFlagEnabled() function itself is implemented, it looks something like this (simplified version for demonstration purposes):
bool IsBehaviorFlagEnabled(const char * fileName)
{
// Note: a real implementation would find the user's home directory
// using the proper API and not just rely on ~ to expand to the home-dir path
std::string filePath = "~/MyProgram_Settings/";
filePath += fileName;
FILE * fpIn = fopen(filePath.c_str(), "r"); // i.e. does the file exist?
bool ret = (fpIn != NULL);
fclose(fpIn);
return ret;
}
The idea being that if you want to change your program's behavior, you can do so by creating a file (or folder) in the ~/MyProgram_Settings directory with the appropriate name. E.g. if you want to enable your Extensions API, you could just do a
touch ~/MyProgram_Settings/enable_extensions_api
... and then re-start your program, and now IsBehaviorFlagEnabled("enable_extensions_api") returns true and so your Extensions API is enabled.
The benefits I see of doing it this way (as opposed to parsing a .ini file at startup or something like that) are:
There's no need to modify any "central header file" or "registry file" every time you add a new behavior-flag.
You don't have to put a ParseINIFile() function at the top of main() in order for your flags-functionality to work correctly.
You don't have to use a text editor or memorize a .ini syntax to change the program's behavior
In a pinch (e.g. no shell access) you can create/remove settings simply using the "New Folder" and "Delete" functionality of the desktop's window manager.
The settings are persistent across runs of the program (i.e. no need to specify the same command line arguments every time)
The settings are persistent across reboots of the computer
The flags can be easily modified by a script (via e.g. touch ~/MyProgram_Settings/blah or rm -f ~/MyProgram_Settings/blah) -- much easier than getting a shell script to correctly modify a .ini file
If you have code in multiple different .cpp files that needs to be controlled by the same flag-file, you can just call IsBehaviorFlagEnabled("that_file") from each of them; no need to have every call site refer to the same global boolean variable if you don't want them to.
Extra credit: If you're using a bug-tracker and therefore have bug/feature ticket numbers assigned to various issues, you can creep the elegance a little bit further by also adding a class like this one:
/** This class encapsulates a feature that can be selectively disabled/enabled by putting an
* "enable_behavior_xxxx" or "disable_behavior_xxxx" file into the ~/MyProgram_Settings folder.
*/
class ConditionalBehavior
{
public:
/** Constructor.
* #param bugNumber Bug-Tracker ID number associated with this bug/feature.
* #param defaultState If true, this beheavior will be enabled by default (i.e. if no corresponding
* file exists in ~/MyProgram_Settings). If false, it will be disabled by default.
* #param switchAtVersion If specified, this feature's default-enabled state will be inverted if
* GetMyProgramVersion() returns any version number greater than this.
*/
ConditionalBehavior(int bugNumber, bool defaultState, int switchAtVersion = -1)
{
if ((switchAtVersion >= 0)&&(GetMyProgramVersion() >= switchAtVersion)) _enabled = !_enabled;
std::string fn = defaultState ? "disable" : "enable";
fn += "_behavior_";
fn += to_string(bugNumber);
if ((IsBehaviorFlagEnabled(fn))
||(IsBehaviorFlagEnabled("enable_everything")))
{
_enabled = !_enabled;
printf("Note: %s Behavior #%i\n", _enabled?"Enabling":"Disabling", bugNumber);
}
}
/** Returns true iff this feature should be enabled. */
bool IsEnabled() const {return _enabled;}
private:
bool _enabled;
};
Then, in your ExtensionsAPI.cpp file, you might have something like this:
// Extensions API feature is tracker #4321; disabled by default for now
// but you can try it out via "touch ~/MyProgram_Settings/enable_feature_4321"
static const ConditionalBehavior _feature4321(4321, false);
// Also tracker #4222 is now enabled-by-default, but you can disable
// it manually via "touch ~/MyProgram_Settings/disable_feature_4222"
static const ConditionalBehavior _feature4222(4222, true);
[...]
void DoTheExtensionsAPIStuff()
{
if (_feature4321.IsEnabled() == false) return;
[... otherwise do the extensions API stuff ...]
}
... or if you know that you are planning to make your Extensions API enabled-by-default starting with version 4500 of your program, you can set it so that Extensions API will be enabled-by-default only if GetMyProgramVersion() returns 4500 or greater:
static ConditionalBehavior _feature4321(4321, false, 4500);
[...]
... also, if you wanted to get more elaborate, the API could be extended so that IsBehaviorFlagEnabled() can optionally return a string to the caller containing the contents of the file it found (if any), so that you could do shell commands like:
echo "opengl" > ~/MyProgram_Settings/graphics_renderer
... to tell your program to use OpenGL for its 3D graphics, or etc:
// In Renderer.cpp
std::string rendererType;
if (IsDebugFlagEnabled("graphics_renderer", &rendererType))
{
printf("The user wants me to use [%s] for rendering 3D graphics!\n", rendererType.c_str());
}
else printf("The user didn't specify what renderer to use.\n");