⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 form1.cs

📁 VC#编写的例程
💻 CS
📖 第 1 页 / 共 2 页
字号:
            // 
            // StartBtn
            // 
            this.StartBtn.BackColor = System.Drawing.Color.Aquamarine;
            this.StartBtn.Location = new System.Drawing.Point(223, 136);
            this.StartBtn.Name = "StartBtn";
            this.StartBtn.Size = new System.Drawing.Size(128, 20);
            this.StartBtn.TabIndex = 3;
            this.StartBtn.Text = "Start";
            this.StartBtn.UseVisualStyleBackColor = false;
            this.StartBtn.Click += new System.EventHandler(this.StartBtn_Click);
            // 
            // EndPointsComboBox
            // 
            this.EndPointsComboBox.DropDownHeight = 120;
            this.EndPointsComboBox.FormattingEnabled = true;
            this.EndPointsComboBox.IntegralHeight = false;
            this.EndPointsComboBox.Location = new System.Drawing.Point(111, 15);
            this.EndPointsComboBox.Name = "EndPointsComboBox";
            this.EndPointsComboBox.Size = new System.Drawing.Size(240, 21);
            this.EndPointsComboBox.TabIndex = 0;
            this.EndPointsComboBox.SelectedIndexChanged += new System.EventHandler(this.EndPointsComboBox_SelectedIndexChanged);
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(16, 18);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(94, 13);
            this.label5.TabIndex = 11;
            this.label5.Text = "Endpoint . . . . . . . ";
            // 
            // CPULoadBox
            // 
            this.CPULoadBox.Controls.Add(this.CpuLabel);
            this.CPULoadBox.Controls.Add(this.CpuBar);
            this.CPULoadBox.Location = new System.Drawing.Point(19, 247);
            this.CPULoadBox.Name = "CPULoadBox";
            this.CPULoadBox.Size = new System.Drawing.Size(330, 60);
            this.CPULoadBox.TabIndex = 12;
            this.CPULoadBox.TabStop = false;
            this.CPULoadBox.Text = " CPU Load ";
            // 
            // CpuLabel
            // 
            this.CpuLabel.AutoSize = true;
            this.CpuLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.CpuLabel.Location = new System.Drawing.Point(150, 41);
            this.CpuLabel.Name = "CpuLabel";
            this.CpuLabel.Size = new System.Drawing.Size(27, 13);
            this.CpuLabel.TabIndex = 1;
            this.CpuLabel.Text = "0 %";
            this.CpuLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // CpuBar
            // 
            this.CpuBar.ForeColor = System.Drawing.Color.ForestGreen;
            this.CpuBar.Location = new System.Drawing.Point(16, 28);
            this.CpuBar.Name = "CpuBar";
            this.CpuBar.Size = new System.Drawing.Size(294, 10);
            this.CpuBar.Step = 1;
            this.CpuBar.TabIndex = 0;
            // 
            // PerfTimer
            // 
            this.PerfTimer.Enabled = true;
            this.PerfTimer.Interval = 500;
            this.PerfTimer.Tick += new System.EventHandler(this.PerfTimer_Tick);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(374, 329);
            this.Controls.Add(this.CPULoadBox);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.EndPointsComboBox);
            this.Controls.Add(this.StartBtn);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.FailuresBox);
            this.Controls.Add(this.SuccessBox);
            this.Controls.Add(this.QueueBox);
            this.Controls.Add(this.PpxBox);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "C# USB Data Streamer";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            this.Load += new System.EventHandler(this.Form1_Load);
            this.groupBox1.ResumeLayout(false);
            this.CPULoadBox.ResumeLayout(false);
            this.CPULoadBox.PerformLayout();

            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			try			{				Application.Run(new Form1());			}			catch (Exception e)			{
                MessageBox.Show(e.StackTrace, "Exception '" + e.Message + "' thrown by " + e.Source);
            }		}


		private void AboutItem_Click(object sender, System.EventArgs e)
		{
			string assemblyList =  Util.Assemblies;			MessageBox.Show(assemblyList,Text);				}

		private void ExitItem_Click(object sender, System.EventArgs e)
		{
			Close();
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
            if (EndPointsComboBox.Items.Count > 0)
                EndPointsComboBox.SelectedIndex = 0;
		}

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (usbDevices != null)
                usbDevices.Dispose();
        }


        // Enforces valid values for PPX
        private void PpxBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (EndPoint == null) return;

            int ppx = Convert.ToUInt16(PpxBox.Text);
            int len = EndPoint.MaxPktSize * ppx;

            int maxLen = 0x10000; // 64K
            if (len > maxLen)
            {
                ppx = maxLen / EndPoint.MaxPktSize / 8 * 8;
                PpxBox.Text = ppx.ToString();
                MessageBox.Show("Maximum of 64KB per transfer.  Packets reduced.", "Invalid Packets per Xfer.");
            }

            if (MyDevice.bHighSpeed && (EndPoint.Attributes == 1) && (ppx < 8))
            {
                PpxBox.Text = "8";
                MessageBox.Show("Minimum of 8 Packets per Xfer required for HS Isoc.", "Invalid Packets per Xfer.");
            }

        }

        private void EndPointsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the Alt setting
            string sAlt = EndPointsComboBox.Text.Substring(4, 1);
            byte a = Convert.ToByte(sAlt);
            MyDevice.AltIntfc = a;

            // Get the endpoint
            int aX = EndPointsComboBox.Text.LastIndexOf("0x");
            string sAddr = EndPointsComboBox.Text.Substring(aX, 4);
            byte addr = (byte)Util.HexToInt(sAddr);

            EndPoint = MyDevice.EndPointOf(addr);

            // Ensure valid PPX for this endpoint
            PpxBox_SelectedIndexChanged(sender, null);
        }


        private void StartBtn_Click(object sender, System.EventArgs e)
        {
            if (MyDevice == null)
                return;

            if (StartBtn.Text.Equals("Start"))
            {
                StartBtn.Text = "Stop";
                StartBtn.BackColor = Color.Pink;

                BufSz = EndPoint.MaxPktSize * Convert.ToUInt16(PpxBox.Text);
                QueueSz = Convert.ToUInt16(QueueBox.Text);
                PPX = Convert.ToUInt16(PpxBox.Text);

                EndPoint.XferSize = BufSz;

                if (EndPoint is CyIsocEndPoint)
                    IsoPktBlockSize = (EndPoint as CyIsocEndPoint).GetPktBlockSize(BufSz);
                else
                    IsoPktBlockSize = 0;

                bRunning = true;

                tListen = new Thread(new ThreadStart(XferThread));
                tListen.IsBackground = true;
                tListen.Priority = ThreadPriority.Highest;
                tListen.Start();
            }
            else
            {
                if (tListen.IsAlive)
                {
                    StartBtn.Text = "Start";
                    bRunning = false;

                    t2 = DateTime.Now;
                    elapsed = t2 - t1;
                    xferRate = (long)(XferBytes / elapsed.TotalMilliseconds);
                    xferRate = xferRate / (int)100 * (int)100;

                    tListen.Abort();
                    tListen.Join();
                    tListen = null;

                    StartBtn.BackColor = Color.Aquamarine;
                }

            }

        }

        // Data Xfer Thread entry point
        public unsafe void XferThread()
        {
            // Setup the queue buffers
            byte[][] cmdBufs = new byte[QueueSz][];
            byte[][] xferBufs = new byte[QueueSz][];
            byte[][] ovLaps = new byte[QueueSz][];

            int xStart = 0;

            try
            {
                LockNLoad(ref xStart, cmdBufs, xferBufs, ovLaps);
            }
            catch (NullReferenceException e) 
            {
                // This exception gets thrown if the device is unplugged 
                // while we're streaming data
                this.Invoke(handleException);
            }
        }


        // This is a recursive routine for pinning all the buffers used in the transfer in memory.
        // It will get recursively called QueueSz times.  On the QueueSz_th call, it will call
        // XferData, which will loop, transferring data, until the stop button is clicked.
        // Then, the recursion will unwind.
        public unsafe void LockNLoad(ref int j, byte[][] cBufs, byte[][] xBufs, byte[][] oLaps)
        {
            // Allocate one set of buffers for the queue
            cBufs[j]    = new byte[CyConst.SINGLE_XFER_LEN + IsoPktBlockSize];
            xBufs[j]    = new byte[BufSz];			oLaps[j]	= new byte[20];

            fixed (byte* tL0 = oLaps[j], tc0 = cBufs[j], tb0 = xBufs[j])  // Pin the buffers in memory
            {
                OVERLAPPED* ovLapStatus = (OVERLAPPED*)tL0;
                ovLapStatus->hEvent = (uint)PInvoke.CreateEvent(0, 0, 0, 0);

                // Pre-load the queue with a request
                int len = BufSz;
                EndPoint.BeginDataXfer(ref cBufs[j], ref xBufs[j], ref len, ref oLaps[j]);

                j++;

                if (j < QueueSz)
                    LockNLoad(ref j, cBufs, xBufs, oLaps);  // Recursive call to pin next buffers in memory
                else
                    XferData(cBufs, xBufs, oLaps);          // All loaded. Let's go!

            }

        }

        // The infinite transfer loop
        public unsafe void XferData(byte[][] cBufs, byte[][] xBufs, byte[][] oLaps)
        {
            int k = 0;
            int len = 0;

            Successes = 0;
            Failures = 0;

            XferBytes = 0;
            t1 = DateTime.Now;

            for (; bRunning; )
            {
                // WaitForXfer
                fixed (byte* tmpOvlap = oLaps[k])
                {
                    OVERLAPPED* ovLapStatus = (OVERLAPPED*)tmpOvlap;
                    if (!EndPoint.WaitForXfer(ovLapStatus->hEvent, 500))
                    {
                        EndPoint.Abort();
                        PInvoke.WaitForSingleObject(ovLapStatus->hEvent, 500);
                    }
                }

                // FinishDataXfer
                if (EndPoint.FinishDataXfer(ref cBufs[k], ref xBufs[k], ref len, ref oLaps[k]))
                {
                    XferBytes += len;
                    Successes++;
                }
                else
                    Failures++;


                // Re-submit this buffer into the queue
                len = BufSz;
                EndPoint.BeginDataXfer(ref cBufs[k], ref xBufs[k], ref len, ref oLaps[k]);

                k++;

                if (k == QueueSz)  // Only update displayed stats once each time through the queue
                {
                    k = 0;

                    t2 = DateTime.Now;
                    elapsed = t2 - t1;

                    xferRate = (long)(XferBytes / elapsed.TotalMilliseconds);
                    xferRate = xferRate / (int)100 * (int)100;

                    // Call StatusUpdate() in the main thread
                    this.Invoke(updateUI);

                    // For small QueueSz or PPX, the loop is too tight for UI thread to ever get service.   
                    // Without this, app hangs in those scenarios.
                    Thread.Sleep(1);
                }

            } // End infinite loop

        }

        // The callback routine delegated to updateUI.
        public void StatusUpdate()
        {
            if (xferRate > ProgressBar.Maximum)
                ProgressBar.Maximum = (int)(xferRate * 1.25);

            ProgressBar.Value = (int)xferRate;
            ThroughputLabel.Text = ProgressBar.Value.ToString();

            SuccessBox.Text = Successes.ToString();
            FailuresBox.Text = Failures.ToString();
        }

        // The callback routine delegated to handleException.
        public void ThreadException()
        {
            StartBtn.Text = "Start";
            bRunning = false;

            t2 = DateTime.Now;
            elapsed = t2 - t1;
            xferRate = (long)(XferBytes / elapsed.TotalMilliseconds);
            xferRate = xferRate / (int)100 * (int)100;

            tListen = null;

            StartBtn.BackColor = Color.Aquamarine;

        }

        // Updates the CPU Load meter
        private void PerfTimer_Tick(object sender, EventArgs e)
        {
            if (bVista) return;

            float cpu = CpuCounter.NextValue();
            CpuBar.Value = (int)cpu;
            CpuLabel.Text = string.Format("{0} %", (int)cpu);

        }

	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -