Visual C++ Thread? - visual-studio-2010

I have a Visual C++ forms application for Windows, using Visual Studio 2010. I want to fire off a thread under this event:
private: System::Void Form1_Shown(System::Object^ sender, System::EventArgs^ e) {
}
How can I do this? I have been searching for hours and it doesn't seem to work for me :( can someone show me how I need to set up a thread that runs another method, and how to set up that method, and everything else (declarations, namespaces you use, etc)?

If you want to explore Visual C++, you will probably be better off working with unmanaged C++, and creating your application using the Win32 API and MFC for the GUI. C++/CLI is a very powerful language, but it basically requires you to know both C++ and C# before you even get started.
That said, here's how you do it:
using namespace System;
using namespace System::Threading;
static void MyThreadFunc()
{
// Insert code to be run on the other thread here.
}
void Form1_Shown(Object^ sender, EventArgs^ e)
{
Thread^ thread = gcnew Thread(gcnew ThreadStart(&ClassName::MyThreadFunc));
// If MyThreadFunc is an instance method, use "gcnew ThreadStart(this, &ClassName::MyThreadFunc)" to get the delegate.
thread->Start();
}

Related

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/

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

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.

How to run a single class in a console inside my MS visual studio 2012

I have the following class:-
public Class test{
public void testmethod(int i)
{
i = 56789121;
//code ges here
Console.WriteLine(i);
} }
but i need to run this class an see the result of the Console.writeline,, but i am not sure how i can do this. i usually build a web application using MS visual studio and run the application by clicking on "start" button,, but i have never try to output the result using Console.writeline.
BR
Build a Console application instead.
File -> Add -> New Project... and select Console Application
Change the .cs file that VS produces to be something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Test
{
public void MyMethod()
{
Console.WriteLine("Hello World!");
}
}
class Program
{
static void Main(string[] args)
{
new Test().MyMethod();
}
}
}
The usual way to do this, as Nigel suggested, is to make a Console App for testing stuff.
However, as you stated, you can't do this from VS Web. I personally have started using LINQPad for one-off testing of my objects:
http://www.linqpad.net/
Once you open it, switch the Language dropdown to "C# Statement(s)" or "C# Program". Hit F4, browse to and add a reference to your DLL and an Import for your namespace. Now you can dim your object and call its methods right from LINQPad. LINQPad will not lock any files, so if you rebuild from VS, you can Alt-Tab back to LINQPad and re-run, and it will use the copy of the library you just build.
I've switched almost exclusively to this, as LINQPad has a really nice interface for exploring objects and exceptions you've .Dump()'ed to the output window.
(No, I'm not affiliated with LINQPad, I'm just a really satisfied customer.)
Alternatively....
Since the C# compiler is part of the .Net framework, and not Visual Studio, you can compile programs on the command line.
For example take the standard HelloWorld program in C#
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello world!");
}
}
Create this in notepad, and save as HelloWorld.cs,
Open a command prompt and add the .net framework folder to your path (if not already there):
C:\> PATH=%PATH%;C:\Windows\Microsoft.NET\Framework\v4.0.30319
(note your .net version above may vary)
Then compile using the following command:
C:\> csc HelloWorld.cs
to create HelloWorld.exe.

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.

WPF Application crashes on WIndows 7 when command executable.Start() is run

I've got a tiny Portal I´m writing, and this portal is supposed to launch installers on button click. I´m developing on VS2010 on a WinXP SP3 station, and on this machine, even fter compilation and publishing, everything works as expected. However, when i run the compiled application in Windows 7, it crashes...The application work, it just crashes when i click a button for program installation.
The programming looks like this:
private void button_access_Click(object sender, RoutedEventArgs e)
{
Process executable = new Process();
string executablePath = "D:\\Visual Studio 2010\\SAFE_Portal1\\SAFE_Portal1\\Extra Programs\\AccessRT2003.exe";
executable.StartInfo.FileName = executablePath;
executable.Start();
}
It specifically crashes on thr button_access_Click procedure...
Any ideas as to why this could be? I`ve tried looking around here in Stackoverflow, and in other forums, but to no avail...
Any help or direction is ganz welcome!
Try this:
try
{
Process executable = new Process();
string executablePath = "D:\\Visual Studio 2010\\SAFE_Portal1\\SAFE_Portal1\\Extra Programs\\AccessRT2003.exe";
executable.StartInfo.FileName = executablePath;
executable.Start();
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
What message are you getting?
Are you sure you want to use fixed paths in your application? If so you should at least check if the file you try to start exists beforehand. Otherwise an exception will be thrown which could be the problem here.
if (File.Exists(executablePath))
{
...
}

Resources