Diamonddrake 397 Master Poster

It's different on a per language basis, but in most languages:

Braces {} are generally for object notation and grouping.
they define an object. Such as when you use them to define a class, enum, stuct ect.
Or for enclosing a memeber or code group, such as a method or property.

In your example:

string[] Meats = { "Roast Beef", "Salami", "Turkey", "Ham", "Pastrani" };

This is an object notation. It's not short hand specifically for creating an array, you can actually create any object this way.

public class myobject
    {
      public string Title {get; set;}

      public bool isInit {get; set;}
    }

    //create shorthand:
    myobject mo = new myobject(){Title="mytitle", isInit=false};

Brackets [] are indexers
when an object can be indexed, the [] supply a selector for the index.
When decaling a type, adding [] to the end is stating that you want an indexable array.
The only other time you will see brackets in C# is for flags. Sometimes when you define a class or interface you will want to flag the members for serialiaztion such as if you wanted to ignore a property in a class you would use the [XmlIgnore()] flag.

public class myobject
    {
       [XmlIgnore()]
       public bool ShipmentSpecified
       { get; set; }
    }

Parentheses () are used in math, casting, grouping, and calling.

Mainly () are for parameters. They are used to denote a situation where a parameter could be passed or recieved. This is most …

iConqueror commented: thankyou that was very helpful +1
Diamonddrake 397 Master Poster

Ok, putting all your logic code that was in the on paint into the timer event was very simple, just a copy and paste and it worked without a fuss. still flickered with a bacground and then I found that you were invalidating the panel from the paint event (you should never do that) So i removed that call from the logic loop and now the background doesn't flicker.

the move speeds need to be modified but other than that, it does seem to work.

I'll email it to you.

Diamonddrake 397 Master Poster

I seemed to have found my answer :) But I can only test on Windows 7 and vista because I don't have an XP Machine. Can someone with an XP machine test this snippet for me and tell me if it works.

class Program

    {

        public static class KnownFolder

        {

            public static Guid Desktop = new Guid("B4BFCC3A-DB2C-424C-B029-7FE99A87C641");

        }

 

        [DllImport("shell32.dll")]

        private extern static int SHSetKnownFolderPath(ref Guid folderId, uint flags, IntPtr token, [MarshalAs(UnmanagedType.LPWStr)] string path);

        [DllImport("Shell32.dll")]

        public static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);

 

        static void Main(string[] args)

        {

            string newPath = @"path to new desktop folder";

            int flags = 0;

            SHSetKnownFolderPath(ref KnownFolder.Desktop, (uint)flags, IntPtr.Zero, newPath);

            SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);

        }

    }
Diamonddrake 397 Master Poster

I am working on a combination productivity and source/version control app. One of the features i would like to add might sound crazy, but I would like to substitute the User's windows Desktop folder with the project files "Working Directory" That way, until the the software is exited, or the project is closed. The windows desktop, the easiest location to find regardless of what you are doing, will be your project folder (If only I had a magic desk that only showed me stuff I needed when I needed it :)

In windows vista and 7 its easy to accomplish this in explorer, in the properties for special folders like the desktop there is a location tab that allows you to change the folder, it works immediately and very well. With the exception of renaming the folder you set to Desktop, it works exactly how I would like it too.

But I can't seem to find out how to accomplish this programmatically. I have tried changing the "shell folder" HKCU registry entry, and although this works for everything but the literal desktop. I can't seem to get the actual desktop desktop to display the changes.

Anyone have any ideas?

Diamonddrake 397 Master Poster

If the items in the list box get hightlight when you hit the keys this sounds like that form isn't getting your keydowns, but the listbox is because its focused. In the designer, click on the form's title bar to select it, then in the property inspector set the form's "KeyPreview" property to true. This will make the parent form get the key event instead of just the selected control in this case the listbox.

That should do it.

jonsca commented: Nice one +6
Diamonddrake 397 Master Poster

sometimes there is a separate process, service, or pool of processes that serve no other purpose but to make sure that no matter a certain process is still running. this is often called a babysitter process. Many many viruses have them. So when you kill it, it starts again.

So long as you identify your bad processes well, then I imagine it can't be any more harmful than the virus itsself.

you still want to throw some thread.sleeps in the loop to slow done the repeat rate.

best of luck.

Diamonddrake 397 Master Poster

The reason your loop eats up the proc is because you are running an infinite loop with While(true) you should be using some kind of reachable goal While(somevalue == true) that way you can break the loop by reaching a goal. If you throw a Thread.Sleep(500) in the loop, you will allow the loop to sleep, easing the usage of the proc and letting the OS prioritize another process for CPU usage.

the cancellation is a little different. you have to put a if statement in the loop, on every itteration you should check the CancelationPending property of the background worker. this will tell you if backgroundworker.CancelAsync has been called.

http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx

It's a fairly simple process.

BTW. its not the best idea to be constantly looping and killing processes. You can put the system in a bad place, especially if the process you are killing has a babysitter or crash protection service attached to it.

Diamonddrake 397 Master Poster

A project I am working needed a question style message box, but I wanted that contemporary look of Vista and Seven. I set out to see how it was accomplished, turns out there are some special APIs that exist in Vista and Seven that don't exist in XP that accomplish that look. This isn't what I hoped for. I want an interface that looks contemporary even in XP.

So I decided to create a very simple messagebox type form that had the appearance of the vista/seven question dialogs, the simplest way possible. This is my result. it uses the multiline label control I already posted here, but I included all the code here for simplicity.

I wanted that windows forms MessageBox.Show() static simplicity. So I created a static class that creates an instance of the messagebox with overloaded constructors to make it simple.

its as easy as

if (QuestionBox.Show("Example Caption", "Example question?", "Example Description") == DialogResult.Yes)
                {
                    //do something
                }

best part is, all managed, no extra api calls, and it looks identical in XP, Vista, and windows 7

kvprajapati commented: Helpful! +11
cale.macdonald commented: Very clean, concise, well written +2
Diamonddrake 397 Master Poster

Apparently there are properties build into the open and save file dialog boxes for doing this.

// Add Pictures custom place using GUID.
    openFileDialog1.CustomPlaces.Add("33E28130-4E1E-4676-835A-98395C3BC3BB");

    // Add Links custom place using GUID
    openFileDialog1.CustomPlaces.Add(
        new FileDialogCustomPlace(
        new Guid("BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968")));

    // Add Windows custom place using file path.
    openFileDialog1.CustomPlaces.Add(@"c:\Windows");

    openFileDialog1.ShowDialog();

But for a more global approach you can modify the registry.

http://www.auxtools.com/placesbar.html

ddanbe commented: He, we should definitly meet in a bar someday ! +8
Diamonddrake 397 Master Poster

I think its the concept your are struggling with, its just as important to know how code works, as it is to know how to use it. Before you jump into something complicated it helps to write some pseudo code showing the steps involved in a process before you ever write any real code.

Also, for small controls, like a textbox, its fine to use the control to store the data like a string. and not save it anywhere else. But when you are working with a good amount of data that you need to manipulate. It helps to create a List of objects and just use the listview control to display that data. not keep track of it.

basic pseudo:
onLoad
- Create a List<myObject> to hold your working data.
- check for a saved file, and populate that List with data from it.
- populate a listview with the data from your List.

onItemAdded
- add the item to the List.
- add the item to the listview.

onClose
- save the List to a file

It's a good practice to write support methods, like a method that takes an List<t> and populate a listview the way you like it. and of course methods that load and save the data, like earlier ones in this thread. I personally like XMLSerialization, but plain text is faster. Its just more complicated and it doesn't save your data as …

Diamonddrake 397 Master Poster

the substring is an instance method of type string that takes an indexed start int and returns that character in the string to the end.

so, if string line = "size=2699309";
then line.SubString(5) would count to the index of 5 or the the 6th character in the string and return that character til the end of the string.

s(0)i(1)z(2)e(3)=(4)2(5)699309

since the 2 in 2699309 is in the Index position of 5. the 2 til the end of the string is return as a new string 2699309

MasterGberry commented: Perfect explanation +1
Diamonddrake 397 Master Poster

I needed a very simple multi-line label control for a project I was working on, It had very simple requirements. It needed to draw text in any font, in any color, on multiple lines with vertical and horizontal alignment control.

So I hacked up this little class. Just as easy to use as a standard label control.

kvprajapati commented: Cool code. +11
ddanbe commented: Cool code indeed! +8
Diamonddrake 397 Master Poster

if all you need is a simple hotkey combination, why even go the route of a low level keyboard hook? Windows has a HotKey api for this very situation.

Here is a simple but usable rewrite of some code I hacked up for one of my projects

//API Imports
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(
            IntPtr hWnd, // handle to window    
            int id, // hot key identifier    
            KeyModifiers fsModifiers, // key-modifier options    
            Keys vk    // virtual-key code    
            );

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd, // handle to window    
            int id      // hot key identifier    
            );

        const int HOTKEY_ID = 31197; //Any number to use to identify the hotkey instance

        public enum KeyModifiers        //enum to call 3rd parameter of RegisterHotKey easily
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }
        
        public bool setHotKey(KeyModifiers Kmds, Keys key)
        {
            return RegisterHotKey(this.Handle, HOTKEY_ID, Kmds, key);
        }

        public bool unSetHotKey()
        {
            return UnregisterHotKey(this.Handle, HOTKEY_ID);
        }

        const int WM_HOTKEY = 0x0312;//magic hotkey message identifier

        protected override void WndProc(ref Message message)
        {
            switch (message.Msg)
            {
                case WM_HOTKEY:
                    Keys key = (Keys)(((int)message.LParam >> 16) & 0xFFFF);
                    KeyModifiers modifier = (KeyModifiers)((int)message.LParam & 0xFFFF);

                    //put your on hotkey code here
                    MessageBox.Show("HotKey Pressed :" + modifier.ToString() + " " + key.ToString());
                    //end hotkey code

                    break;

            }
            base.WndProc(ref message);
        }

        //put this code in the onload method of your form
           setHotKey(KeyModifiers.Alt | KeyModifiers.Shift, Keys.S);

        //and set up a form closed event and call
            unSetHotKey();
kvprajapati commented: Perfect! +11
Diamonddrake 397 Master Poster

I am working on an application that lets you play drum sounds using a rockband drum kit. Current version available here I am wanting to add a recording function but all I can think of is loop back recording. That's manageable but in Vista and Windows 7 by default the stereo mix recording source is disabled.

Does anyone know how to loopback record without it enable, or how to programmatically enable it? I know screen cap apps do it somehow, but I cant find any concrete examples of how to accomplish this.

kvprajapati commented: Have you tried any open source lib? +11
Diamonddrake 397 Master Poster

There is no reason why you can't, but it depends on the accessibility you need for the enum. If the namespace directly contains the enum than any object in that namespace has access to the enum. When its contained in a class, depending on its access modifier it may or may not be available to all the objects in that namespace.

Typically you would put the enum inside the class if the class encapsulates the extent of the usage of the enum. If the enum has common items to the application that don't explicitly require the use of the class then its up to the developer to make the call.

Diamonddrake 397 Master Poster

That low level input hook is some tasty stuff, But if you are new to writing applications outside of forms and want simple, that example is far from simple.

The hardest part of writing a good gui free application is that the .net framework won't manually create an event loop for you, so you'll have to create one yourself. That's a bit tricky and unnecessary. You can use a hidden blank form to host the event loop for your application in which case you can use the very simple registerHotKey windows API to handle all your key presses, if you don't want to use a blank form, you can use it as a debug form with a hotkey to show it for app variable information, or as an about box so you can easily tell the version number and list all the shortcuts in the event there are many.

its just an alternate idea, But I would also like to note that the low level system hook described in adatapost's link is a good solid way to handle this as well, it can just get tricky.

kvprajapati commented: To the point. Very good explanation! +11
Diamonddrake 397 Master Poster

a wrapper is just an object that acts as a middle ground to communicate with a library, program, or api to simplify its use, they are all different. The .net framework is a big wrapper for windows core functions. All programming involves the abstraction, whether its a layer you created, or one someone else did.

This forum is for helping, but you have to ask a direct question, "how does this work:, "What is this?", or "Does any one want to help?" questions typically don't get answered. Post a particular question about something you need help with and it will be read. and if anyone knows they will post a reply.

kvprajapati commented: nice answer :) +10
Diamonddrake 397 Master Poster

That was my solution :) I still prefer GDI+ and win forms. WPF's drawing technique has much better performance, But on a todays machines its typically not a big deal. I have done some pretty amazing custom controls in GDI+.

Diamonddrake 397 Master Poster

I personally never got into WPF, I like my old winform applications.

in C# you can't do true gradient transparency but you can achieve that look a multitude of ways. If you set the formborderstyle to none and set an image as a background you can use a color key to make a single color transparent like any gif image on the web does. to bring that further to light you can layer your form and add true full 255 levels of transparency but that requires 2 forms one for the border and another for the use-able part of the form. Looks great but gets complicated, then the last honorable option would be to capture the desktop and draw it on any transparent areas and use that as the form's background.

Anyway, once you get your borders looking how you want you just create custom buttons that have the desired effect for the Minimize/maximize/close.

Anyway, Attached is an example of using an image with a transparency key, custom image rollover buttons for shell, with all the code there, even for moving the form. I was working on this for an article that I never got around to working on. I'm sure its right up your alley. It even includes the photoshop psd files of the images i created.

i hope it servers you well.

nssltd commented: Thanks just what i needed plus i like the minature shell design you added in on the project its so simple yet so effective :D +1
Diamonddrake 397 Master Poster

Be sure to add an automatic database backup feature! And if it were mine i would grab one of those open source PDF libraries and add an "Export to PDF" feature so it will be simple for her to share her recipes with friends and family!

Of course you could consider storing information about the recipes in a DB and storing the actual recipes themselves in a plaintext format with a different extention in a monitored subfolder of the user's documetns folder. making it very easy to back up and share the recipes, you could then have these recipe documents automatically open with your software with the option of coping it to that user's recipes folder and adding the information to the collection!

Just some suggestions. This sounds like a great idea :)

Geodude0487 commented: Great advice!! Never would've thought about this on my own. +1
Diamonddrake 397 Master Poster

interesting article sknake, but titus i can agree that its a LOT of code. I wouldn't worry about the overhead of a TCP socket, Each user isn't going to have 120 open convertsations. As sknake pointed out, UDP is best used for live streams like audio. If you were to add a skype feature to your chat app. you would certainly want that p2p UDP connection. But just for text. TCP is best.

Using the P2P system you are pointing out would put significantly less stress on the server. But the question here is, are you planning to have 20,000 users? If not, having the server handle everything would be fine, assuming you created a nice thread pool that would cycle through pending messages and deploy them.

Its always nice to have your tools handle the trouble spots for you. like apps that generate objects based on xml schemas and tools that create asynchronous methods from a class or even compiled code. But it doesn't hurt when in a learning environment to try and do it by hand, just so you really know what's going on, how it works, and why it there.

Regardless, no matter how neat it is to make a chat application, unless you really feel like you can compete with Yahoo, Aim, MSNMessenger, Trillian, and Pidgin. Then its just a learning experience anyways. In which case, dive in and make mistakes that you learn from.

Diamonddrake 397 Master Poster

I see now that threads you have posted in have a bullseye and are inversed when they are new. But when I first stumbled upon a thread that I had started. It didn't have that icon. It just had a purple circle with the word "new" in it. Although now it is acting as it should. So my gripe is gone. Great job!

Diamonddrake 397 Master Poster

I Dig the new appearance. But there used to be a tiny pencil icon that made it quite obvious that you had posted in a thread before. I relied on that icon for years. Not that its gone. I'm frustrated.

Other than that. Its a welcome change.

Diamonddrake 397 Master Poster

I miss the little pencil icon that made it very obvious that you had posted in a thread.

Diamonddrake 397 Master Poster

Well for starters you are using 2 separate stream objects, and using them quite oddly.

you should just be using 1 NetworkStream object instead of your stream reader and writer objects. NetworkStream clientstream = client.GetStream() This will allow you to read and write to the network with one object and its also important that you always write Bytes to the stream. you can't just write text to the stream you need to convert the text to a byte array in a buffer and send it in chunks. small strings it doesn't matter much. But if it were an entire paragraph you aren't going to get 1 to 1 writes and reads.

But none of that really matters. It doesn't work because your two application use DIFFERENT PORTS! your client is trying to connect to port 1000 while your server is listening on port 4296. Change the port in the connect method of the client app to match the listener on the server and you should be good to go. assuming that you have your ports forwarded on your network, unless of course you use local host.

Also your threading is kinda sketchy, but it should work. that application.doevents() appears to be used in an odd fashion. See what you can do with the information i have given you. If you can't get it working right I will go back and edit the projects and re-post them. I would have already done that. But you are doing a …

Diamonddrake 397 Master Poster

You'll need to throw a contol, like a panel, in the area you want the arrow to be drawn in. Then hook up its paint event. Then use the event's painteventargs object to access the panel's graphics object. and use the graphic's objects drawline method to draw from point to point. Drawing curves are a little more complicated as then you need to draw Arcs and they take a complicated set of params to achieve a desired effect. But all the documentation is there. its just about making it happen.

Diamonddrake 397 Master Poster

Not like I don't have 100 unfinished projects already. But I recently come across a mario paint composer by unfungames.com. I remember playing mario paint back on the Snes. So I gave it a whirl. Turns out they wrote it in macromedia director. and it sucks. It does what its suppose to but the interface is buggy and it just doesn't work right. So I come across mario sequencer. its in Japanese it works ok, but it lacks all the features that would make it worth while.

So I decided I would attempt to make my own. I know using directSound with a secondary audio buffer you can alter the pitch of a wav file. no problem there. I drew the staff already using gdi+, no problem there. but then the problem comes with how do I loop through the objects added to the staff?

Here is my idea. I'm just not sure the performance will be worth the time. Any suggestions would be appreciated.

I used 20px gaps vertically and 40px gaps horizontally. I figure i create a "note" class that holds its point to be drawn on the staff. and when you click to add a note it will check the point you clicked and move it to the next even 40px interval for x and 20px interval for y causing it to snap to the staff. I the note class a frequency variable that is automatically set depending on its postiton.Y property. and give …

Diamonddrake 397 Master Poster

the problem with finding new and interesting ways to hide your data is that in attempts to thwart virus attacks and unwanted software Microsoft has limited the access to many areas of the registry and hard-disk. So that keeps you from getting too creative.

there is NO guaranteed way. If someone knows their way around windows well enough they will always be able to find a way around your trial version. if you name the registry entry something that has nothing to do with your application, then its going to be less likely a user will find it with a simple search. but using programs that watch for changes in the registry when a program is installed or first run. they can find your registry entry and can change it.

if you save your data to a file, they can still find it and changed it. which leads to the newest method used by Adobe. the internet validation. Every time you open PhotoShop CS4. it connects to the internet and checks if the user's key is a valid key, and if it isn't then the program wont work, if the app can't get to the net. it simply works. but you could easily make your app not work if that were the case. Then when people download your app, or first run it. you could have it contact a webserver and create a key for them, attach to that information when the evaluation started, and use the server. …

Diamonddrake 397 Master Poster

Its a good IDE. but its not the only free alternative to Visual Studio for .net projects. besides the obvious Visual C#.net free from Microsoft there is also SharpDevelop. http://www.icsharpcode.net/OpenSource/SD/ I don't use it primarily as my preference is Visual studio. But its amazing and also open source.

Not knocking monodevelop. I have used all 3 of these and they all have their ups and downs, But they all are wonderful IDEs. I recommend Visual Studio first and foremost as it always supports the newest trends as soon as they are available. But otherwise, both SharpDevelop and MonoDevelop are great too.

I'm also a fan of snippetCompiler too, although i no longer use it because i wrote my own version that opens faster, supports more languages, and saves file tabs between session via a checkbox below the close button.

On another note, there is a free Adobe Flash open source IDE called FlashDevelop that is pretty nifty too. Its a good time for open software with the boom in computer science students about.

Diamonddrake 397 Master Poster

I think your best bet here is to make your app run in the background with a system tray Icon. Using a timer and on its tick, subtract the time you started from the current time. then compare that a timespan.

attached is an example app project. I figured I'd need this for something eventually so I went ahead and hacked up and example.

Diamonddrake 397 Master Poster

According to the method definition for "tellme" that you show here, the 2nd param is of type Elephant. Which happens to be the type of the class that holds that method.

So when you call Tellme, and pass to it "this" you are passing a reference to the instance of an elephant class that the method is called from.

so when you call
lucinda.SpeakTo(lloyd, "Hello");
what is happen is, this method uses, lloyd(an instance of an Elephant) to get to its TellMe method. When you call the Tellme method of lloyd, you pass to lloyd the original method, but then it wants to know WHO sent that message(who called that method) So you say "THIS" since "THIS" is called from inside lucinda, THIS = lucinda who is of type elephant.

Sorry if I am confusing you. I hope you get it.

"this" always refers to the class you call it from.
If you are inside of a class, and you call "this" you are referring to the particular instance of that class as it is called at runtime.

So. if you are in lucinda, and you call "this" than this = lucinda.
if you are in lloyd and you call "this" than this = lloyd.

Also, the parameters aren't named very well to be easily undestood.
Instead of "talkTo" it should be ElephantToTalkTo. So when you pass lloyd, to the method, you are passing the elephant reference.

ddanbe commented: Nice explanation. +6
Diamonddrake 397 Master Poster

baeltazor, I see you are accustom to the .net baby sitter as much as I am. :). C and C++ people don't tend to use foreach loops often when the migrate to .net because its only possible in programming languages that use virtual machines like .net's CLR. But it actually adds an overhead, slowing down the execution of the code. Plus your version of the code requires creating an addition object, that takes time to initialize, takes more system resource, and twice the memory.

Not that its a bad way to do it. computers these days are plenty fast and for each loops and they are very fun and easy to use.

But even though its less typing, technically the OP's way of doing it was "faster" by terms of the program execution.

Diamonddrake 397 Master Poster

*sigh*

string path =  Application.StartupPath;
string subfolder = @"\Images\";
string imagefilename = "myjpeg.jpg";

pictureBox.Image = Image.FromFile(path + subfolder + imagefilename);
Diamonddrake 397 Master Poster

I have never heard the term "Push Tech" but To my knowledge most chat applications go through the server for everything. But there is a possible peer to peer relationship that can be established.

Normally. The client messengers contact the server. the server has a thread pool of sockets blocking waiting to accept new client connections. Then once the handshake is made, the socket with the client connection is passed to a thread pool for redirecting messages. And the client's login name is added to a list. Then when a client sends a message to another client. It actualy is sending the message to the server like"attention:client name: message" the server then write that message to the socket for that intended client. The client has a thread constantly blocking on a socket read waiting for new mesagges. once it gets one it shows it to the user and goes back to blocking on a socket read. and the gui thread is always open to write outgoing messages or update the display.

now in a server logged peer2peer situation, Clients connect to a server just to tell the server where they are, who they are, and what they can do, and get a list of that information about other logged in clients. So then each client has the information it needs to make a direct connection to other clients. But this requires ports to be opened and other hassles. But it keeps the load off the server, so a …

kvprajapati commented: Indeed. +9
Diamonddrake 397 Master Poster

This simple class encapsulates the exAnimatewindow api call. I got tired of adding all the jazz to every form I need to use as a pop up, or any borderless forms I used. (Windows 7 and vista don't animate windows with no border by default)

This class could easily be expanded to offer all the animation directions and types But I included just the ones I use most often. I like a small footprint. No need for code you don't use. So just expand it if you need more functionality.

here is the simple usage. Just throw this line in the constructor of the form you wish to animate.

DDFormsExtentions.WindowAnimator DDwa = new DDFormsExtentions.WindowAnimator(this, DDFormsExtentions.WindowAnimator.AniType.SlideDown, 200);
kvprajapati commented: Wonderful! +9
Diamonddrake 397 Master Poster

IDK about that one. COM works with running apps. but I'm afraid that's where my usefulness here looses speed. Sorry. Hope you find your answer.

Diamonddrake 397 Master Poster

Yes you can. That's what I explained before. Create a public class with a pubic method GetBookReference(string book) or whatever you want. Compile it. and start a new application. Click on references. Click new reference. and browse to the first exe. then use the GetBookReference(string book) method. That simple. Just try it

that is assuming that you are using Visual Studio 2008. I believe older versions of Visual studio limits you to .dll even then you can manually add a reference using compiler arguments.

I just tested it in Visual studio 2008 to verify that it works, and it does.

Diamonddrake 397 Master Poster

the 2nd form should expose the selected data as properties. when the user has set the values they wanted. the dialogresult property should be set to OK. and the form closed. Nothing else needs to happen in the 2nd from. The main form will still have a reference to the 2nd form and be able to get its data.

Diamonddrake 397 Master Poster

call the open file dialog box in the program's Main method. if its a success then call the application.run method passing the filename to the form's constructor. if its not a success then simple allow the main method to return closing the program.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Serial
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1(ofd.FileName));
            }
        }
    }
}
Geekitygeek commented: word for word what i would have post :p +1
Diamonddrake 397 Master Poster

Create a Static Class and make the method static. Then at any time in the application you simply call it [I]Classname[/I].[I]Methodname[/I]([I]parms[/I]); . that easy.

Diamonddrake 397 Master Poster

I need to count the ticks from a simple switch attached to a gauge. The time it takes from the first detected tick to the 20th is the important data. To acquire the cycling on and off of the switch i have come up with 2 serial port techniques.

1) use the ready to send voltage through the switch and constantly poll in 10ms intervals the clear to send pin for its value and use that to determine the cycling.

2)loop pins 2 and 3 (- in and out) through the switch, constantly writing a character and using the datarecived event to increment a count. and using a checkcount from a timer to determin the cycling of the switch.

My question is, which one of these would be the best route? obviously (1) is the simplest. But I can't seem to determine which is the most accurate system. I don't have much knowledge of the speed and reliability of Serial Port communications and uses. Any thoughts beyond speculation would be appreciated. I have 2 working solutions. I need the most accurate. I have done testing and I can't see to figure which works best. And although the difference is minute, its important that I use the most accurate and reliable method.

Diamonddrake 397 Master Poster

I needed a 5 minute countdown for a project I was working on so I hacked this up, It does nothing more and nothing less. Figured I would post it while I was here to save someone else the trouble. (Not that it's in anyway difficult to do.)

ddanbe commented: Nice! +6
Diamonddrake 397 Master Poster

Sounds like homework :) lol.

This is so easy. rig up your mouse down and mouse up events and create class variables of type Point. Then get the mouse coordinates with the event arguments on mouse down, save it to the first. then on mouse up get the mouse coordinates with the event arguments and save it to the second Point var. then rig up an onPaint event and simply call the drawLine method of the graphics class from the first to the 2nd point. and don't forget to invalidate the form at then end of the mouse up.

Best of luck. This is too easy to just post the answer. Give it a shot. you can handle it.

ddanbe commented: Good answer! +6
Diamonddrake 397 Master Poster

And just for fun I modified some code from that link and here is a class that you can simply call the "isWave" method and it will return true/false :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace CheckMimeForWav
{
    class MimeCheck
    {

        [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
        private extern static System.UInt32 FindMimeFromData(
            System.UInt32 pBC,
            [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
            [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
            System.UInt32 cbSize,
            [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
            System.UInt32 dwMimeFlags,
            out System.UInt32 ppwzMimeOut,
            System.UInt32 dwReserverd
        );

        public string getMimeFromFile(string filename)
        {
            if (!File.Exists(filename))
                throw new FileNotFoundException(filename + " not found");

            byte[] buffer = new byte[256];
            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                if (fs.Length >= 256)
                    fs.Read(buffer, 0, 256);
                else
                    fs.Read(buffer, 0, (int)fs.Length);
            }
            try
            {
                System.UInt32 mimetype;
                FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
                System.IntPtr mimeTypePtr = new IntPtr(mimetype);
                string mime = Marshal.PtrToStringUni(mimeTypePtr);
                Marshal.FreeCoTaskMem(mimeTypePtr);
                return mime;
            }
            catch (Exception e)
            {
                return "unknown/unknown";
            }
        }

        public bool isWave(string FileName)
        {
            if ("audio/wav" == getMimeFromFile(FileName))
            {
                return true;
            }
            else
            {
                return false;
            }
        }


    }
}
ddanbe commented: Great! +6
Diamonddrake 397 Master Poster

I am working on a really fun project. I have written much of a program that lets you use a RockBand or GuitarHero drum kit to play drum sounds on your PC, record, playback, ect. I have decided conclusively as I add features I need more than just a gui thread calling async play sound methods. I need extensive threading here and for the most part I know what to do.

But I have a Metronome class that uses async media timer and playsound methods. but still has trouble being accurate if something else on the form slows down the message loop. So I have started a new thread that uses Application.Run() to start that thread with its own message loop. then creates the timer class, starts it and hooks up an event. then in the event it calls the playsoundAsync method.

So now I have 2 problems, How do I safely change the timer objects Interval property from the GUI thread? and then How do I safely stop this type of thread? the standard while loop practice is useless here because I am using a MessageLoop to process events.

I have most often used threading to do some finite task that will return when its done. This is a new practice for me using threads to insure an accurate "on-beat" playing of audio.

I have lots of code bouncing around in my head, I just want some insight before I make a mess. Searching the …

Diamonddrake 397 Master Poster

here is the code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace DaniwebThreading.DancingLabels
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Thread draw;

        private void Form1_Load(object sender, EventArgs e)
        {
            draw = new Thread(new ThreadStart(Display));
            draw.Start();
        }

        public void Display()
        {
           bool doloop = true;
           int X;
           int Y;

            Random objRandom = new Random();
           // for (int index = 1; index <= 100000; index++) //use while loop to keep it going forever!
            while(doloop)
            {
                X = objRandom.Next(200);
                Y = objRandom.Next(200);
                moveLabel(new Point(X, Y));
                Thread.Sleep(500);
            }
        }

        public delegate void MoveLabelDelegate(Point P);

        public void moveLabel(Point P)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MoveLabelDelegate(moveLabel), P);
            }
            else
            {
                lblMessage.Location = P;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            draw.Abort(); //kill the thread.
        }
    }
}

you need a delegate to usher the call on to the GUI thread by calling invoke. The trick here is creating a method that will check if its required, and if so invoke its self using the delegate. Its a good idea to create these type methods for all the controls you with to update information for.

The form closing event here is used to abort the thread so you don't get an exception when you close the form where the draw thread is still trying to modify the disposed control.

Threading gets complicated. Good luck with your endeavors.

Diamonddrake 397 Master Poster

Threading is a very complicated thing, and you can't access a control from another thread than the one it was created on which is almost always the GUI thread, or the thread that is started when the application runs.

The best idea here is to build a application modal that doesn't rely on the controls hosing the information, but just displaying it.

you have given no information about your error, just the error message and that's USELESS out of context. It could be that you need to pass a list of files or something to the worker thread as an object, or it could be that you need to use a delegate and invoke a call onto the control. But Its hard to tell. Post your code, We will help you.

Diamonddrake 397 Master Poster

Just use this method to download the html and save it to a variable, then parse out the IMG tags and save that to another variable. Then have a button that switches between them and loads the selected one into the webbrowser.

Diamonddrake 397 Master Poster

They are not downloaded at all, its just the text.

The browser first makes an tcp http request and asks for the text, That is what you have done with the get http method here. Then the browser parses the html and decides what it should look like and what else it needs to download from the server. Since you remove the IMG tags before you pass the html to the browser control the request for the images is never made.

Diamonddrake 397 Master Poster

I don't know of anywhere that would have done this already but I'm sorry as I don't know

here is a class that lets you get the Title from an html document

public class WebHelper 
    { 
        public static string FetchHTML(string sUrl) 
        { 
            System.Net.WebClient oClient = new System.Net.WebClient(); 
            return oClient.DownloadString(sUrl); 
            //return new System.Text.UTF8Encoding().GetString(oClient.DownloadData(sUrl)); 
        } 
 
        public static string FetchTitleFromHTML(string sHtml) 
        { 
            string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)"; 
            System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(regex, System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
            return ex.Match(sHtml).Value.Trim(); 
 
        } 
 
    }

using the fetch HTML to get the text and then using the string.Replace method can get rid of the "<IMG SRC=" tags and just how the URL of the image in instead. just load that string into the WebBrowser control and you should be golden.

user20000 commented: Diamonddrake rocks! Thanks mate! +0
Geekitygeek commented: great solution +1