C# Auf der Suche nach coolen Funktionen

NSR

Mitglied
Sers Community.
Das hier ist kein 'Frage'-Thread sondern ein Sammel-Thread.
Und zwar geht es darum Code hineinzuschreiben, der witzige, coole oder einfach nur hilfreiche Funktionen ausführt. Mit der Begründung was der machen soll. (Bei komplizierteren Sachen mögl. auch ne Erklärung dazu). Wenn ihr der Meinung seid, dass ihr nen besseren Weg kennt eine Funktion durchzuführen, dass Postet sie einfach mit einem Verweis auf die alte Funktion.

Ich fang gleich mal an auch als Beispiel:
Und zwar bewirkt der Code, dass man ein Programm nur einmal Starten kann.
Also nicht einmal starten und dann ist des Programm futsch :), sondern dass man das Programm wenns schon läuft nicht noch einmal starten kann.

Der Code wird im Programm.cs eingefügt (erste if()else() anweisung, im else steht der normale Application.Run teil.)


Code:
                /// <summary>
		/// Der Haupteinstiegspunkt für die Anwendung.
		/// </summary>
		[STAThread]
		static void Main()
		{
			if (RunningInstance() != null)
			{	// Meldung ausgeben
				MessageBox.Show("This program can not be executed repeatedly.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				// Programminstanz schließen
				Application.Exit();
			}
			else
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new Main());
			}
		}
		/// <summary>
		/// Prüfen ob Programminstanz bereits ausgeführt wird
		/// </summary>
		/// <returns>falls ja, Programminstanz, falls nein, null</returns>
		public static Process RunningInstance()
		{
			/*Prüft, ob das Programm schon läuft - Alle Prozesse mit dem Namen des aktuellen Prozesses holen*/
			System.Diagnostics.Process[] processes = Process.GetProcesses();

			/*Alle Prozesse durchgehen und den Fenstertitel vergleichen*/
			string mainProcessTitle = "TS700.Protokollverwaltung";
			for (int i = 0; i < processes.Length; i++)
			{
				/*Den aktuellen Prozess ausschließen*/
				if (processes[i].Id != Process.GetCurrentProcess().Id)
				{
					if (processes[i].ProcessName == mainProcessTitle)
					{
						/*Prozess gefunden, diesen zurückgeben*/
						return processes[i];
					}
				}
			}
			/*Kein Prozess gefunden, der dem aktuellen entspricht, also null zurückgeben*/
			return null;
		}

Hoffe der Thread kommt gut an. In Hoffnung auf ein paar coole Funktionen.
Grüße Nico
 
Ich habe eine Alternative zum Eröffnungsthread (Programm nur einmal starten):
C#:
static void Main()
{
    Mutex mutex = new Mutex(true, "MyApplication");
                        
    if( !mutex.WaitOne(0, false) )
    {
        Debug.WriteLine("Application is already running!");
    }
    else
    {
        Application.Run( new MyMainForm() );
        mutex.ReleaseMutex();
    }
}
Gruß
MCoder
 
  • Gefällt mir
Reaktionen: NSR
Nachdem hier (leider) niemand mehr was postet, hau ich halt noch einmal einen Raus.
(Das ist ein Programm, dass eine eigene Oberfläche hat. Folgt lieber erst einmal den Anweisungen, bevor ihr es in euer Programm integriert. (Dafür müsst ihr es sowieso ein wenig abändern.))
Hiermit kann mit Windows-Word auf Rechtschreibfehler geprüft werden. (Findet ihr auch unter: http://msdn.microsoft.com/de-de/library/ms173188(VS.80).aspx )
Achtung: Word muss natürlich installiert sein!

1. Erstellen Sie in Visual Studio ein neues C#-Windows-Anwendungsprojekt, und nennen Sie es WordRechtschreibung.

2. Kopieren Sie den Code direkt hier darunter, und fügen Sie ihn anstelle des bisherigen Inhalts in die Datei Form1.cs ein.

Code:
using System.Reflection;
using Word = Microsoft.Office.Interop.Word;

namespace WordSpell
{
    public partial class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label1;

        public Form1()  //constructor
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            Word.Application app = new Word.Application();

            int errors = 0;
            if (textBox1.Text.Length > 0)
            {
                app.Visible = false;

                // Setting these variables is comparable to passing null to the function.
                // This is necessary because the C# null cannot be passed by reference.
                object template = Missing.Value;
                object newTemplate = Missing.Value;
                object documentType = Missing.Value;
                object visible = true;

                Word._Document doc1 = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
                doc1.Words.First.InsertBefore(textBox1.Text);
                Word.ProofreadingErrors spellErrorsColl = doc1.SpellingErrors;
                errors = spellErrorsColl.Count;

                object optional = Missing.Value;

                doc1.CheckSpelling(
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional,
                    ref optional, ref optional, ref optional, ref optional, ref optional, ref optional);

                label1.Text = errors + " errors corrected ";
                object first = 0;
                object last = doc1.Characters.Count - 1;
                textBox1.Text = doc1.Range(ref first, ref last).Text;
            }

            object saveChanges = false;
            object originalFormat = Missing.Value;
            object routeDocument = Missing.Value;

            app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
        }
    }
}

Kopieren Sie den unteren Code, und fügen Sie ihn in die Datei Form1.Designer.cs in der InitializeComponent()-Methode hinter den vorhandenen Inhalt ein.

Code:
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
// 
// textBox1
// 
this.textBox1.Location = new System.Drawing.Point(40, 40);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(344, 136);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
// 
// button1
// 
this.button1.Location = new System.Drawing.Point(392, 40);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Check Spelling";
this.button1.Click += new System.EventHandler(this.button1_Click);
// 
// label1
// 
this.label1.Location = new System.Drawing.Point(40, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(336, 16);
this.label1.TabIndex = 2;
// 
// Form1
// 
this.AutoScaleDimensions = new System.Drawing.SizeF(5, 13);
this.ClientSize = new System.Drawing.Size(496, 205);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "SpellCheckDemo";
this.ResumeLayout(false);

Fügen Sie dem Projekt einen Verweis auf die Word-Assembly hinzu. Klicken Sie mit der rechten Maustaste auf das Projekt, klicken Sie auf Verweis hinzufügen, und klicken Sie im Dialogfeld Verweis hinzufügen auf die Registerkarte COM. Doppelklicken Sie auf Objektbibliothek für Microsoft Office 11, und klicken Sie auf OK.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Bevor ihr jetzt aufschreit "Hey da steht doch genau des gleiche wie auf der MSDN-Seite" des stimmt schon, aber der thread ist ja nicht nur für eigene Funktionen gemacht, sondern für alle, die ihr für nützlich erachtet.

Grüße und in Hoffnung auf weitere Beiträge Nico.
 
Zuletzt bearbeitet:
du hast von eigener Oberfläche geredet, ich dachte da gibts dann irgendwas cooles zu sehen :D

Edit:
ah sry hatte gestern das Word über lesen.
War da grad frisch vom training zurück.
 
Ein kleines Progrämmchen, um mal alle Farben der Color-Struktur anzuzeigen.

Gruß
MCoder

C#:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Reflection;

namespace ColorTable
{
    static class Program
    {
        #region Main
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new ColorView());
        }
        #endregion Main
        
        #region ColorView
        private class ColorView : Form
        {
            #region members
            private TableLayoutPanel m_oPanel = new TableLayoutPanel();
            #endregion members
        
            #region construction
            public ColorView()
            {
                Size = new Size(800,600);
                Text = "Color Table";
            
                m_oPanel.Dock        = DockStyle.Fill;
                m_oPanel.AutoScroll  = true;
                m_oPanel.ColumnCount = 1;
                m_oPanel.GrowStyle   = TableLayoutPanelGrowStyle.AddRows;

                SetColors();
                
                Controls.Add(m_oPanel);
            }
            #endregion construction

            #region methods
            private void SetColors()
            {
                Color sColor = new Color();
                PropertyInfo [] aProperties = sColor.GetType().GetProperties();
                
                foreach( PropertyInfo oProperty in aProperties )
                {
                    if( oProperty.PropertyType == typeof(Color) )
                    {
                        Color sNextColor = (Color)oProperty.GetValue(sColor, null);
                    
                        if( !sNextColor.ToString().Contains("Transparent") )
                        {
                            Label oLbColor = new Label();
                            
                            oLbColor.Height      = 40;
                            oLbColor.BorderStyle = BorderStyle.Fixed3D;
                            oLbColor.TextAlign   = ContentAlignment.MiddleCenter;
                            oLbColor.Dock        = DockStyle.Fill;
                            oLbColor.ForeColor   = (sNextColor.GetBrightness() >= 0.5) ? Color.Black :
                                                                                         Color.White;
                            oLbColor.BackColor   = sNextColor;
                            oLbColor.Text        = CreateCaption(sNextColor);
                            
                            m_oPanel.Controls.Add(oLbColor);
                        }
                    }                    
                }
            }

            private string CreateCaption(Color sColor)
            {
                return String.Format( "{0}     {1},{2},{3}     {1:X2}{2:X2}{3:X2}",
                                      sColor.ToString().Split(new char [] { '[', ']' })[1],
                                      sColor.R,
                                      sColor.G,
                                      sColor.B );                 
            }
            #endregion methods
        }
        #endregion ColorView   
    }
}
 
Zurück