Why can't I use STAThread attribute in C++/CLI? - visual-studio

I wan to use the STAThread attribute on my the main thread of my program. However, Visual Studio says it cannot find it. I have tried references necessary assemblies and using proper namespace, but it just can't find it.
Edit:
I have been able to get to work successfully after manually creating a thread with the
ApartmentState to STA. I think this is the equivalent to setting the thread, be it the main thread, but not exactly because i'm creating another thread. Anyone have another way to do this.
Here is the code:
void threadStart ()
{
Application::Run (gcnew GraphicsForm());
}
[System::STAThread] // This will not work!
int main(array<System::String ^> ^args)
{
Thread ^t = gcnew Thread(gcnew ThreadStart (threadStart));
t->ApartmentState = ApartmentState::STA;
t->Start();
return 0;
}

When I create a new C++/CLI project in Visual Studio 2012 with only a single main() function and then add [System::STAThread] in front of main(), it compiles and runs without a problem. To me, this means that it is most likely a settings difference between projects.
My recommendation is to do the same thing. Create a new C++/CLI project, add [System::STAThread] and see if it has any issues. If not, then you're at the point of checking the differences between the two projects to determine why one works properly and the other is giving you an error.

Related

C++ Windows Forms application icon exception

I want to set an icon for my Windows Form application. My actions step by step:
I created an 'icon.ico' (256x256) and put it into my project folder
In my 'Form1.h [Design]' I chose this file using Properties
This code appeared in 'Form1.h'
void InitializeComponent(void)
{ ...
this->Icon = (cli::safe_cast<System::Drawing::Icon^>(resources->GetObject(L"$this.Icon")));
... }
The object '$this.Icon' appeared in 'Form1.resx'
I rebuilt the whole project -> no errors
During execution the line 'this->Icon = ...' causes an exception: System.Resources.MissingManifestResourceException: 'Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "WinForm.Form1.resources" was correctly embedded or linked into assembly "MyProject" at compile time, or that all the satellite assemblies required are loadable and fully signed.'
Here I found numerous advices, such as remove/add icon or set some custom properties for 'Form1.resx', but none of them works for me
Just like above, change line to:
this->Icon = gcnew System::Drawing::Icon(L"ICON_NAME.ico");
You might get error/exception while opening form creator but you shouldn't lose any data.
Been there, done that :)
Place the Icon you want to connect to your Form in the project directory.
Then replace the line above with the following:
this->Icon = gcnew System::Drawing::Icon(L"app.ico");
This should neutralize the bug that Microsoft has not fixed.
If you are using visual studio 2019 , you need to change the name of namespace in Form1 the same as your project name, i did it and it works
and make sure you change it in main :
[STAThread]
int main() {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Application::Run(gcnew your_namespace_name::Form1());
return 0;
}

Can I pass an argument/switch/parameter to a VSPackage MenuCommand?

I was hoping someone here might be able to help me out with this. I'm not the most experienced programmer but I'm making progress on a project.
I've got a need to programmatically interact with Visual Studio. Some success has been had using EnvDTE Interop stuff, but it seems that some of what I need to do needs to be done inside VS so I'm attempting to utilize a VSPackage MenuCommand to do various things. Sorry the vagueness.
I'm currently successfully creating a custom MenuCommand with a VSPackage extension, and also am able to trigger that MenuCommand programmatically from another application using the DTE.
What I'm wondering is: is it possible to define a MenuCommand that CAN take arguments passed along to it from the triggering external application?
Using the VS Package Template in Visual Studio 2012 using the Menu Command option, all my code lives inside this method:
private void MenuItemCallback(object sender, EventArgs e)
{
// my code...
}
There is obviously a lot of other auto-generated code plumbing this all together, but all MY code lives in this method. Is there a way to alter this method so that it will allow parameters to be passed to it? What other changes must I make to the other files to declare/register this differently-functioning method once I do so (if I can)?
For example:
static void Main(string[] args)
{
Type visualStudioType = Type.GetTypeFromProgID("VisualStudio.DTE.11.0");
DTE dte = Activator.CreateInstance(visualStudioType) as DTE;
dte.MainWindow.Visible = true;
dte.ExecuteCommand("myCommand");
}
This works. But what I'd like to do is change that last command to:
dte.ExecuteCommand("myCommand", "myArguments");
When I attempt to do something like this, I receive the following exception:
"Command \"myCommand\" does not accept arguments or switches."
Sorry if I'm not being clear. Any help would be greatly appreciated.
Commands created from add-ins accept parameters by default.
Commands created from packages need to specify the <CommandFlag>AllowParams</CommandFlag> when defining the command in the .vsct file. See: http://msdn.microsoft.com/en-us/library/bb491716.aspx
And see also this thread:
IOleComandTarget::exec for commands with parameters
https://social.msdn.microsoft.com/Forums/en-US/134983e8-049c-40e1-a212-312fa637698b/iolecomandtargetexec-for-commands-with-parameters?forum=vsx
Then, it should work, either using dte.ExecuteCommand or dte.Commands.Raise(...). See:
HOWTO: Pass parameters programmatically to a command from a Visual Studio add-in
http://www.visualstudioextensibility.com/articles/add-ins/

How Can I Add an "ATL Simple Object" to Old ATL DLL Project Upgraded to VS 2010?

We have a DLL project which has existed for a long time (maybe as far back as Visual Studio 6) which has been updated for each new version of VS. The project contains a number COM classes implemented using ATL.
After upgrade to VS 2010, the project still builds fine. However, if I try to right-click the project and choose Add -> Class... -> ATL Simple Object, I get an error box that says this:
ATL classes can only be added to MFC EXE and MFC Regular DLL projects or projects with full ATL support.
This worked in VS 2008.
When I look at the project properties, Use of MFC was set to Use Standard Windows Libraries and Use of ATL was set to Not Using ATL. I changed these to Use MFC in a Shared DLL and Dynamic Link to ATL respectively, but still get the same error.
I know how to add new ATL objects without using the wizard, and I could try to recreate the project from scratch using VS 2010 to make it happy. But does anyone know of any easy way to get VS to allow me to use the ATL Simple Object wizard with a project that it doesn't recognize as a project "with full ATL support"?
Check this thread out.
It seems that adding this fragment info your ATL C++ code make it work. You don't need to actually build the project, just remove this stuff away after you are done with the wizard (provided that solution works for you).
// Added fake code begins here
class CAppModule :
public CComModule
{
};
// Added fake code ends here, below is regular ATL project stuff
CAppModule _Module;
This is where it all comes from, in $(VisualStudio)\VC\VCWizards\1033\common.js:
/******************************************************************************
Description: Returns a boolean indicating whether project is ATL-based.
oProj: Project object
******************************************************************************/
function IsATLProject(oProj)
{
try
{
var oCM = oProj.CodeModel;
oCM.Synchronize();
// look for global variable derived from CAtlModuleT
var oVariables = oCM.Variables;
for (var nCntr = 1; nCntr <= oVariables.Count; nCntr++)
{
var oVariable = oVariables(nCntr);
var strTypeString = oVariable.TypeString;
if (strTypeString == "ATL::CComModule" || strTypeString == "ATL::CAutoThreadModule")
{
return true;
}
Same problem here, but the project source already had CComModule _Module;
Fixed it, based on the IsATLProject script shown above, by changing it to
**ATL::**CComModule _Module;

Any FREE plug-in for VisualStudio that has partial code completion?

VS2010: one thing Resharper has is that in Intellisence when we are typing the name of a method it shows all suggestions that have the words we are typing somewhere in their name so for example if method name is DoSomethingReallyCool() and I am not aware of this exact name but I just type "Really" then the its intelliseinse is also showing DoSomethingReallyCool() as a suggestion. this help me A LOT for coding. I was wondering if there is any FREE plug-in with this capability?
Visual Studio 2010 does this now without a plug in.
Take the following excerpt:
class Program {
static void Main( string[] args ) {
}
static void ReallyCoolFunction() { };
static void SuperCoolFunction() { };
}
If I type Cool inside the main body, both functions show up in the intellisense list.
Doesn't VS2010 already do this? My copy seems to.
If not then The Productivity Power tools may be what does it on my version. If not then it's still a jolly fine add-in anyway.

Why does Debug.Writeline stop working for some projects in the solution?

We have a solution with multiple projects after running the code from VS the output normally seen from Debug.Writeline statements just cease to appear. I mention the multiple projects because the output from one of the projects continues to appear. However, the other project consistently stops showing the output from the statements.
It's starting to drive me crazy. I should mention this is also occurring for a second developer on the project. Anyone seen this before, or have any ideas?
After being tormented by this for years I finally found the cause and the solution in this Stack Overflow question: vs2010 Debug.WriteLine stops working
It seems that Visual Studio's handinlg of debug.writeline can't handle multiple processeses that each use multiple threads correctly. Eventually the 2 processes will deadlock the portion of visual studio that handles the output, causing it to stop working.
The solution is to wrap your calls to debug.writeline in a class that synchronizes across processes using a named mutex. This prevents multiple processes from writing to debug at the same time, nicely side stepping the whole deadlock problem.
The wrapper:
public class Debug
{
#if DEBUG
private static readonly Mutex DebugMutex =new Mutex(false,#"Global\DebugMutex");
#endif
[Conditional("DEBUG")]
public static void WriteLine(string message)
{
DebugMutex.WaitOne();
System.Diagnostics.Debug.WriteLine(message);
DebugMutex.ReleaseMutex();
}
[Conditional("DEBUG")]
public static void WriteLine(string message, string category)
{
DebugMutex.WaitOne();
System.Diagnostics.Debug.WriteLine(message,category);
DebugMutex.ReleaseMutex();
}
}
Or for those using VB.NET:
Imports System.Threading
Public Class Debug
#If DEBUG Then
Private Shared ReadOnly DebugMutex As New Mutex(False, "Global\DebugMutex")
#End If
<Conditional("DEBUG")> _
Public Shared Sub WriteLine(message As String)
DebugMutex.WaitOne()
System.Diagnostics.Debug.WriteLine(message)
DebugMutex.ReleaseMutex()
End Sub
<Conditional("DEBUG")> _
Public Shared Sub WriteLine(message As String, category As String)
DebugMutex.WaitOne()
System.Diagnostics.Debug.WriteLine(message, category)
DebugMutex.ReleaseMutex()
End Sub
End Class
Follow these steps, it works for me
Right click on your project
Select Properties
Select tab Build
Make sure Define DEBUG constant is checked
Hope that helps
I had the same problem with Visual Studio 2010. None of the above solutions worked in my case, but I solved it like this:
Right-click on your project.
Select Properties.
Click the Compile tab.
Scroll down to "Advanced Compile Options".
Change the value for "Generate debug info" from "pdb-only" to
"Full".
No idea what it's for exactly, but now my Debug.Print statements appear in the Immediate Window again I can finally get back to work.
you should try DebugView from Microsoft SystemInternals.
http://technet.microsoft.com/en-us/sysinternals/bb896647
Regards,
Allen
Try checking if Platform for the solution is set to Any CPU and not x86 (or x64). I used x86 to enable Edit and Continue and then lost Debug output. After going back to AnyCPU the Output is also back.
Got this in VS 2015. All of a sudden all Debug.WriteLine "stops working" (not showing in Output window). After going crazy about this for about an hour I found the problem:
1. Right click In output window (output from Debug)
2. Check that "Program output" is checked

Resources