1. Dashboard
  2. Forum
    1. Unerledigte Themen
  3. Downloads
  4. Galerie
    1. Alben
  5. Toolbox
    1. Passwort Generator
    2. Portchecker
  6. Mitglieder
    1. Mitgliedersuche
    2. Benutzer online
    3. Trophäen
    4. Team
Fr: 16 Mai 2025
  • Anmelden oder registrieren
  • Suche
Dieses Thema
  • Alles
  • Dieses Thema
  • Dieses Forum
  • Artikel
  • Forum
  • Dateien
  • Seiten
  • Bilder
  • Erweiterte Suche

Schön, dass du den Weg zu NodeZone.net gefunden hast! Aktuell bist du nicht angemeldet und kannst deshalb nur eingeschränkt auf unsere Community zugreifen. Um alle Funktionen freizuschalten, spannende Inhalte zu entdecken und dich aktiv einzubringen, registriere dich jetzt kostenlos oder melde dich mit deinem Account an.

Anmelden oder registrieren
    1. Nodezone.net Community
    2. Forum
    3. Entwicklung & Scripting
    4. Programmiersprachen
    5. .NET

    [FRAGE] [C#] Webserver erstellen und Scanner ansprechen

    • Natic
    • 7. März 2019 um 13:04
    • Geschlossen
    • Natic
      Fortgeschrittener
      Reaktionen
      66
      Trophäen
      9
      Beiträge
      408
      • 7. März 2019 um 13:04
      • #1

      Moin NN,

      ich möchte über einen Btn eine Webseit erstellen lassen wo 0 und 1 des Scanners der Empfangenen Werte als Text ausgeben wird.

      Der Scanner funktioniert bereits, die 0 und 1 habe ich noch nicht entwickelt.

      Doch wisst ihr wieso keine Webseite erstellt wird?

      Hier der Code:

      C#
      Main.cs
      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Drawing.Imaging;
      using System.Linq;
      using System.Text;
      using System.Windows.Forms;
      using WIATest;
      using System.IO;
      using System.Net;
      using System.Net.Sockets;
      using System.Threading;
      
      namespace Scannerapplication
      {
          public partial class Form1 : Form
          {
      
              public Form1()
              {
                  InitializeComponent();
              }
              //button click event
              private void btn_scan_Click(object sender, EventArgs e)
              {
                  MessageBox.Show("Die Verbindung muss bei jedem neustart erfolgen!");
                  try
                  {
                      //get list of devices available
                      List<string> devices = WIAScanner.GetDevices();
      
                      foreach (string device in devices)
                      {
                          lbDevices.Items.Add(device);
                      }
                      //check if device is not available
                      if (lbDevices.Items.Count == 0)
                      {
                          MessageBox.Show("Es wurden keine WIA Scanner gefunden");
                      }
                      else
                      {
                          lbDevices.SelectedIndex = 0;
                      }
                      //get images from scanner
                      List<Image> images = WIAScanner.Scan((string)lbDevices.SelectedItem);
                      foreach (Image image in images)
                      {
                          pic_scan.Image = image;
                          pic_scan.Show();
                          pic_scan.SizeMode = PictureBoxSizeMode.StretchImage;
                          //save scanned image into specific folder
                          image.Save(@"E:\" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".jpeg", ImageFormat.Jpeg);
                      }
                  }
                  catch (Exception exc)
                  {
                      MessageBox.Show(exc.Message);
                  }
              }
      
      
              private void Home_SizeChanged(object sender, EventArgs e)
              {
                  int pheight = this.Size.Height - 153;
                  pic_scan.Size = new Size(pheight - 150, pheight);
              }
      
              private void btn_start_Click(object sender, EventArgs e)
              {
                  WebServer ws = new WebServer(SendResponse, "http://localhost:8080/index/");
                  ws.Run();
                 // Console.WriteLine("Drücken sie eine Taste um es zu schließen!");
                 // Console.ReadKey();
                  ws.Stop();
              }
              public static string SendResponse(HttpListenerRequest request)
              {
                  return string.Format("<HTML><BODY>BinaryDP<br>{0}</BODY></HTML>", DateTime.Now);
              }
          }
      }
      Alles anzeigen

      Class - WebServer:

      C#
      using System;
      using System.Net;
      using System.Threading;
      using System.Linq;
      using System.Text;
      
      namespace Scannerapplication
      {
          public class WebServer
          {
              private readonly HttpListener _listener = new HttpListener();
              private readonly Func<HttpListenerRequest, string> _responderMethod;
      
              public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
              {
                  if (!HttpListener.IsSupported)
                      throw new NotSupportedException(
                          "Die Server Version ist veraltet");
      
                  // URI prefixes are required, for example 
                  // "http://localhost:8080/index/".
                  if (prefixes == null || prefixes.Length == 0)
                      throw new ArgumentException("prefixes");
      
                  // A responder method is required
                  if (method == null)
                      throw new ArgumentException("method");
      
                  foreach (string s in prefixes)
                      _listener.Prefixes.Add(s);
      
                  _responderMethod = method;
                  _listener.Start();
              }
      
              public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
                  : this(prefixes, method)
              { }
      
              public void Run()
              {
                  ThreadPool.QueueUserWorkItem((o) =>
                  {
                      Console.WriteLine("Webserver running...");
                      try
                      {
                          while (_listener.IsListening)
                          {
                              ThreadPool.QueueUserWorkItem((c) =>
                              {
                                  var ctx = c as HttpListenerContext;
                                  try
                                  {
                                      string rstr = _responderMethod(ctx.Request);
                                      byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                      ctx.Response.ContentLength64 = buf.Length;
                                      ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                                  }
                                  catch { } // suppress any exceptions
                                  finally
                                  {
                                      // always close the stream
                                      ctx.Response.OutputStream.Close();
                                  }
                              }, _listener.GetContext());
                          }
                      }
                      catch { } // suppress any exceptions
                  });
              }
      
              public void Stop()
              {
                  _listener.Stop();
                  _listener.Close();
              }
          }
      }
      Alles anzeigen

      Class - Scanner:

      C#
      using System;
      using System.Collections.Generic;
      using System.IO;
      using System.Drawing;
      
      namespace WIATest
      {
          class WIAScanner
          {
              const string wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}";
              class WIA_DPS_DOCUMENT_HANDLING_SELECT
              {
                  public const uint FEEDER = 0x00000001;
                  public const uint FLATBED = 0x00000002;
              }
              class WIA_DPS_DOCUMENT_HANDLING_STATUS
              {
                  public const uint FEED_READY = 0x00000001;
              }
              class WIA_PROPERTIES
              {
                  public const uint WIA_RESERVED_FOR_NEW_PROPS = 1024;
                  public const uint WIA_DIP_FIRST = 2;
                  public const uint WIA_DPA_FIRST = WIA_DIP_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
                  public const uint WIA_DPC_FIRST = WIA_DPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
                  //
                  // Scanner only device properties (DPS)
                  //
                  public const uint WIA_DPS_FIRST = WIA_DPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
                  public const uint WIA_DPS_DOCUMENT_HANDLING_STATUS = WIA_DPS_FIRST + 13;
                  public const uint WIA_DPS_DOCUMENT_HANDLING_SELECT = WIA_DPS_FIRST + 14;
              }
              /// <summary>
              /// Use scanner to scan an image (with user selecting the scanner from a dialog).
              /// </summary>
              /// <returns>Scanned images.</returns>
              public static List<Image> Scan()
              {
                  WIA.ICommonDialog dialog = new WIA.CommonDialog();
                  WIA.Device device = dialog.ShowSelectDevice(WIA.WiaDeviceType.UnspecifiedDeviceType, true, false);
                  if (device != null)
                  {
                      return Scan(device.DeviceID);
                  }
                  else
                  {
                      throw new Exception("You must select a device for scanning.");
                  }
              }
      
              /// <summary>
              /// Use scanner to scan an image (scanner is selected by its unique id).
              /// </summary>
              /// <param name="scannerName"></param>
              /// <returns>Scanned images.</returns>
              public static List<Image> Scan(string scannerId)
              {
                  List<Image> images = new List<Image>();
                  bool hasMorePages = true;
                  while (hasMorePages)
                  {
                      // select the correct scanner using the provided scannerId parameter
                      WIA.DeviceManager manager = new WIA.DeviceManager();
                      WIA.Device device = null;
                      foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                      {
                          if (info.DeviceID == scannerId)
                          {
                              // connect to scanner
                              device = info.Connect();
                              break;
                          }
                      }
                      // device was not found
                      if (device == null)
                      {
                          // enumerate available devices
                          string availableDevices = "";
                          foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                          {
                              availableDevices += info.DeviceID + "\n";
                          }
      
                          // show error with available devices
                          throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
                      }
                      WIA.Item item = device.Items[1] as WIA.Item;
                      try
                      {
                          // scan image
                          WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                          WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);
      
                          // save to temp file
                          string fileName = Path.GetTempFileName();
                          File.Delete(fileName);
                          image.SaveFile(fileName);
                          image = null;
                          // add file to output list
                          images.Add(Image.FromFile(fileName));
                      }
                      catch (Exception exc)
                      {
                          throw exc;
                      }
                      finally
                      {
                          item = null;
                          //determine if there are any more pages waiting
                          WIA.Property documentHandlingSelect = null;
                          WIA.Property documentHandlingStatus = null;
                          foreach (WIA.Property prop in device.Properties)
                          {
                              if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
                                  documentHandlingSelect = prop;
                              if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
                                  documentHandlingStatus = prop;
                          }
                          // assume there are no more pages
                          hasMorePages = false;
                          // may not exist on flatbed scanner but required for feeder
                          if (documentHandlingSelect != null)
                          {
                              // check for document feeder
                              if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
                              {
                                  hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
                              }
                          }
                      }
                  }
                  return images;
              }
      
              /// <summary>
              /// Gets the list of available WIA devices.
              /// </summary>
              /// <returns></returns>
              public static List<string> GetDevices()
              {
                  List<string> devices = new List<string>();
                  WIA.DeviceManager manager = new WIA.DeviceManager();
                  foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                  {
                      devices.Add(info.DeviceID);
                  }
                  return devices;
              }
          }
      }
      Alles anzeigen

      Bedanke mich bei jeder Hilfe

      Mit freundlichen Grüßen

      Natic

      --------------------------------------------------------------------------------------------------------------------------

      Kein direkten PN - Support

      --------------------------------------------------------------------------------------------------------------------------

      Programierung

      Wir lieben

      es

    • Natic
      Fortgeschrittener
      Reaktionen
      66
      Trophäen
      9
      Beiträge
      408
      • 7. März 2019 um 17:47
      • #2

      Problem wurde behoben, es sollte nicht in der selben Funktion wieder gestoppt werden :D

      #closed

      Mit freundlichen Grüßen

      Natic

      --------------------------------------------------------------------------------------------------------------------------

      Kein direkten PN - Support

      --------------------------------------------------------------------------------------------------------------------------

      Programierung

      Wir lieben

      es

    Registrieren oder Einloggen

    Du bist noch kein Mitglied von Native-Servers.com? Registriere dich kostenlos und werde Teil einer großartigen Community!

    Benutzerkonto erstellen

    Benutzer online in diesem Thema

    • 1 Besucher

    Wichtige Links & Informationen

    Server & Hosting-Ressourcen

      Server Administration & Hosting Basics

      Windows Server Support & Guides

      Linux Server Configuration & Help

      Setting up TeamSpeak 3 & VoIP Servers

      Domains & Web Hosting for Beginners & Professionals

      Cloud Hosting, Docker & Kubernetes Tutorials

    Gameserver & Modding-Ressourcen

      ArmA 3 Tutorials & Script Collection

      Renting & Operating Gameservers

      DayZ Server Management & Help

      FiveM (GTA V) Server & Script Development

      Rust Server Modding & Administration

      Setting up & Optimizing ARK Survival Servers

    NodeZone.net – Deine Community für Gameserver, Server-Hosting & Modding

      NodeZone.net ist dein Forum für Gameserver-Hosting, Rootserver, vServer, Webhosting und Modding. Seit 2015 bietet unsere Community eine zentrale Anlaufstelle für Server-Admins, Gamer und Technikbegeisterte, die sich über Server-Management, Hosting-Lösungen und Spielemodding austauschen möchten.


      Ob Anleitungen für eigene Gameserver, Hilfe bei Root- und vServer-Konfigurationen oder Tipps zu Modding & Scripting – bei uns findest du fundiertes Wissen und praxisnahe Tutorials. Mit einer stetig wachsenden Community findest du hier Antworten auf deine Fragen, Projektpartner und Gleichgesinnte für deine Gaming- und Serverprojekte. Schließe dich NodeZone.net an und werde Teil einer aktiven Community rund um Server-Hosting, Gameserver-Management und Modding-Ressourcen.

    Wer jetzt nicht teilt ist selber Schuld:
    1. Nutzungsbestimmungen
    2. Verhaltensregeln
    3. Datenschutzerklärung
    4. Impressum
    5. Urheberrechts- oder Lizenzverstoß melden
  • Trimax Design coded & layout by Gino Zantarelli 2023-2025©
    Community-Software: WoltLab Suite™