Commit 1cce736b 几米阳光

CodeLibraryProject为二维码类库,料仓和福霸新焊接机都有引用dll

1 个父辈 adea08a0
正在显示 128 个修改的文件 包含 4971 行增加0 行删除
## Ignore Visual Studio temporary files, build results, and ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons. ## files generated by popular Visual Studio add-ons.
# User-specific files # User-specific files
*.suo *.suo
*.user *.user
......

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2043
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeTest", "CodeLibraryProject\CodeTest\CodeTest.csproj", "{780143A4-7A42-412B-8C70-FB77DCA9396D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "CodeLibraryProject\Common\Common.csproj", "{43CDD09E-FCF3-4960-A01D-3BBFE9933122}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeLibrary", "CodeLibraryProject\CodeLibrary\CodeLibrary.csproj", "{2E0D9598-CB37-46DC-9C9B-D36D4D344451}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Release|Any CPU.Build.0 = Release|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.Build.0 = Release|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {86EE028B-D15B-4A8A-ADC7-599806646D8C}
EndGlobalSection
EndGlobal
using Basler.Pylon;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class PylonCamera
{
private Camera cam = null;
private List<ICameraInfo> allCameras;
private PixelDataConverter conv = new PixelDataConverter();
private Stopwatch stopWatch = new Stopwatch();
private System.Windows.Forms.PictureBox pic;
public PylonCamera()
{
allCameras = CameraFinder.Enumerate();
}
~PylonCamera()
{
Close();
}
public int Index { set; get; }
public string ErrInfo { set; get; }
public int CameraCount
{
get { return allCameras.Count; }
}
public bool IsOpen
{
get { return cam != null; }
}
public string[] GetName()
{
string[] s = new string[allCameras.Count];
for (int i = 0; i < s.Length; i++)
s[i] = allCameras[i][CameraInfoKey.FullName].ToString();
return s;
}
public void Close()
{
if (cam != null)
{
cam.Close();
cam.Dispose();
cam = null;
}
}
public bool Open()
{
return Open(Index);
}
public bool Open(int idx)
{
if (idx < 0 || idx >= allCameras.Count) return false;
if (cam != null) Close();
try
{
Index = idx;
cam = new Camera(allCameras[idx]);
cam.ConnectionLost += OnConnectionLost;
cam.CameraOpened += OnCameraOpened;
cam.CameraClosed += OnCameraClosed;
cam.StreamGrabber.GrabStarted += OnGrabStarted;
cam.StreamGrabber.ImageGrabbed += OnImageGrabbed;
cam.StreamGrabber.GrabStopped += OnGrabStopped;
cam.Open();
//加载用户设置1
cam.Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1);
//执行设置
bool bln = cam.Parameters[PLCamera.UserSetLoad].TryExecute();
return true;
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
}
public void Stop()
{
if (cam != null)
{
cam.StreamGrabber.Stop();
}
}
public Bitmap syncShot()
{
cam.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
cam.StreamGrabber.Start();
IGrabResult grabResult = cam.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
if (!grabResult.IsValid)
{
return null;
}
Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
cam.StreamGrabber.Stop();
return bitmap;
}
public void asynShot( )
{
try
{
cam.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
cam.StreamGrabber.Start(1, GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
}
public void ContinuousShot( )
{
try
{
cam.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
cam.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
}
private void OnConnectionLost(Object sender, EventArgs e)
{
Close();
}
private void OnCameraOpened(Object sender, EventArgs e)
{
}
private void OnCameraClosed(Object sender, EventArgs e)
{
}
private void OnGrabStarted(Object sender, EventArgs e)
{
stopWatch.Reset();
}
private void OnGrabStopped(Object sender, GrabStopEventArgs e)
{
stopWatch.Reset();
}
private void OnImageGrabbed(Object sender, ImageGrabbedEventArgs e)
{
IGrabResult grabResult = e.GrabResult;
if (!grabResult.IsValid)
{ return; }
if (!stopWatch.IsRunning || stopWatch.ElapsedMilliseconds > 33)
{
stopWatch.Restart();
}
Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2E0D9598-CB37-46DC-9C9B-D36D4D344451}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CodeLibrary</RootNamespace>
<AssemblyName>CodeLibrary</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Basler.Pylon, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e389355f398382ab, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\Basler.Pylon.dll</HintPath>
</Reference>
<Reference Include="halcondotnet">
<HintPath>..\dll\halcondotnet.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="zxing">
<HintPath>..\dll\zxing.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Camera.cs" />
<Compile Include="FrmCodeLearn.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeLearn.Designer.cs">
<DependentUpon>FrmCodeLearn.cs</DependentUpon>
</Compile>
<Compile Include="FrmCodeDecode.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeDecode.Designer.cs">
<DependentUpon>FrmCodeDecode.cs</DependentUpon>
</Compile>
<Compile Include="HDCodeHelper.cs" />
<Compile Include="HDCodeLearnHelper.cs" />
<Compile Include="HDLogUtil.cs" />
<Compile Include="ImageHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="FrmCodeLearn.resx">
<DependentUpon>FrmCodeLearn.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmCodeDecode.resx">
<DependentUpon>FrmCodeDecode.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file \ No newline at end of file
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class DHBarCodeHelper
{ /// <summary>
/// 根据图片解析二维码
/// </summary>
/// <param name="ho_Image">Halcon中的图片对象</param>
/// <param name="codeCount">二维码数量</param>
/// <param name="codeParamPath">二维码参数路径,""表示不使用参数</param>
/// <param name="paramType">二维码类型,不传类型默认Data Matrix ECC 200</param>
/// <returns>解析到的二维码</returns>
public static List<CodeInfo> DecodeCode(HObject ho_Image, int codeCount, string codeParamPath, params string[] paramType)
{
List<string> codeType = new List<string>(paramType.ToList());
if (codeType.Count<string>() <= 0)
{
codeType.Add("CODE_39");
}
List<CodeInfo> codeList = new List<CodeInfo>();
foreach (string t in codeType)
{
List<CodeInfo> array = GetCode(ho_Image, t, codeParamPath, codeCount);
codeList.AddRange(array.ToArray<CodeInfo>());
}
return codeList;
}
private static List<CodeInfo> GetCode(HObject ho_Image, string symbolType, string hv_model_path, int codeCount)
{
List<CodeInfo> codeList = new List<CodeInfo>();
try
{
HTuple hv_Area = null;
HTuple hv_Row1 = null;
HTuple hv_Column = null;
HTuple hv_PointOrder = null;
HObject ho_SymbolXLDs;
HTuple hv_ResultHandles = null;
HTuple hv_DecodedDataStrings = null;
HTuple hv_DataCodeHandle = null;
HOperatorSet.GenEmptyObj(out ho_SymbolXLDs);
HOperatorSet.CreateBarCodeModel(symbolType, "default_parameters", "maximum_recognition", out hv_DataCodeHandle);
//string hv_model_path = GetCodeParamFilePath(symbolType);
if (!hv_model_path.Equals("") && File.Exists(hv_model_path))
{
HOperatorSet.ReadDataCode2dModel(hv_model_path, out hv_DataCodeHandle);
}
ho_SymbolXLDs.Dispose();
if (codeCount <= 0)
{
HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
new HTuple(), new HTuple(), out hv_ResultHandles, out hv_DecodedDataStrings);
}
else
{
HOperatorSet.FindDataCode2d(ho_Image, out ho_SymbolXLDs, hv_DataCodeHandle,
"stop_after_result_num", codeCount, out hv_ResultHandles, out hv_DecodedDataStrings);
}
HOperatorSet.AreaCenterXld(ho_SymbolXLDs, out hv_Area, out hv_Row1, out hv_Column, out hv_PointOrder);
if (HalconWindow != null)
{
ShowImage(HalconWindow, ho_Image, ho_SymbolXLDs);
}
HOperatorSet.ClearDataCode2dModel(hv_DataCodeHandle);
string[] resultList = hv_DecodedDataStrings.SArr;
if (resultList.Length > 0)
{
for (int i = 0; i < hv_DecodedDataStrings.SArr.Length; i++)
{
try
{
int x = (int)Math.Round(hv_Column.DArr[i]);
int y = (int)Math.Round(hv_Row1.DArr[i]);
string str = hv_DecodedDataStrings.SArr[i];
CodeInfo code = new CodeInfo(str, x, y);
codeList.Add(code);
}
catch (Exception ex)
{
HDLogUtil.error("处理二维码出错:索引=" + i + "," + resultList.ToString());
}
}
}
return codeList;
}
catch (Exception ex)
{
return codeList;
}
}
}
}

using CodeLibrary;
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace CodeLibrary
{
public partial class FrmCodeDecode : Form
{
private PylonCamera camera = new PylonCamera();
private Stopwatch stopwatch = new Stopwatch();
public FrmCodeDecode()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
cmbCount.SelectedIndex = 0;
string[] camerName = camera.GetName();
cmbCamera.Items.Clear();
foreach (string str in camerName)
{
cmbCamera.Items.Add(str);
}
if (camerName.Length > 0)
{
cmbCamera.SelectedIndex = 0;
}
cmbCodeType.DataSource = HDCodeLearnHelper.codeTypeList;
if (HDCodeLearnHelper.codeTypeList.Count > 0)
{
cmbCodeType.SelectedIndex = 0;
}
else
{
cmbCodeType.Items.Add("QR Code");
cmbCodeType.SelectedIndex = 0;
}
}
private void btnSelImage_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Title = "选择二维码图片";
openDialog.Filter = "图片(*.jpg)|*.jpg|图片(*.png)|*.png|图片(*.bmp)|*.bmp";
//openDialog.DefaultExt = "png";
System.Windows.Forms.DialogResult result = openDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
txtPath.Text = openDialog.FileName;
string filename = txtPath.Text;
if (string.IsNullOrEmpty(filename))
{
MessageBox.Show("获取二维码图片为空");
}
pictureBox1.Image = null;
//读取图片内容
Image img = (Image)Image.FromFile(filename).Clone();
pictureBox1.Image = img;
}
private void button2_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null || txtPath.Text.Equals(""))
{
MessageBox.Show("请先选择图片","提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
Bitmap map = new Bitmap(pictureBox1.Image);
Bitmap newMap = ImageHelper.ConvertTo1Bpp1(map);
pictureBox1.Image = newMap;
}
private void button3_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null || txtPath.Text.Equals(""))
{
MessageBox.Show("请先选择图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Bitmap map = new Bitmap(pictureBox1.Image);
Bitmap newMap = ImageHelper.ToGray(map);
pictureBox1.Image = newMap;
}
private void ShowCode(List<CodeInfo> list)
{
if (list.Count > 0)
{
txtResult.Text += "\r\n识别到二维码:";
foreach (CodeInfo code in list)
{
txtResult.Text += "\r\n" + ""+code.CodeType+" (X:" + code.X + ",Y:" + code.Y + ") " + code.CodeStr;
}
}
else
{
txtResult.Text += "\r\n未识别到二维码";
}
}
private void btnHalconP_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null || txtPath.Text.Equals(""))
{
MessageBox.Show("请先选择图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int count = cmbCount.SelectedIndex + 1;
txtResult.Text = "";
stopwatch.Restart();
HDCodeHelper.HalconWindow = this.hWindowControl1.HalconWindow;
Bitmap map = new Bitmap(pictureBox1.Image);
List<CodeInfo> result = HDCodeHelper.DecodeBarCode(map);
ShowCode(result);
txtResult.Text += "\r\n扫码结束耗时:" + stopwatch.Elapsed.ToString();
}
public void ShowImage(HObject ho_Image)
{
HTuple width, height;
HOperatorSet.GetImageSize(ho_Image, out width, out height);
int dWidth = (int)width.D;
int dHeight = (int)height.D;
this.hWindowControl1.HalconWindow.SetPart(0, 0, dHeight, dWidth);
HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);
}
private void button5_Click(object sender, EventArgs e)
{
FrmCodeLearn frm = new FrmCodeLearn();
frm.ShowDialog();
}
private void button6_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null)
{
MessageBox.Show("请先选择图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int count = cmbCount.SelectedIndex + 1;
txtResult.Text = "";
stopwatch.Restart();
Bitmap map = new Bitmap(pictureBox1.Image);
HObject ho_image = HDCodeHelper.Bitmap2HObjectBpp24(map);
txtResult.Text += "\r\n转换图片耗时:" + stopwatch.Elapsed.ToString();
hWindowControl1.HalconWindow.SetPart(0, 0, map.Height, map.Width);
HOperatorSet.DispObj(ho_image, hWindowControl1.HalconWindow);
ShowImage(ho_image);
HDCodeHelper.HalconWindow = this.hWindowControl1.HalconWindow;
string codeParamPath = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
if (chbUseParam.Checked.Equals(false))
{
codeParamPath = "";
}
List<CodeInfo> codeList = HDCodeHelper.DecodeCode(ho_image, count, codeParamPath,cmbCodeType.Text);
ShowCode(codeList);
txtResult.Text += "\r\n扫码结束耗时:" + stopwatch.Elapsed.ToString();
}
private void button7_Click(object sender, EventArgs e)
{
txtResult.Text = "";
}
private void button8_Click(object sender, EventArgs e)
{
int index = cmbCamera.SelectedIndex;
if (index < 0)
{
MessageBox.Show("请先选择相机");
return;
}
camera.Open(index);
Bitmap bit = camera.syncShot();
if (bit != null)
{
pictureBox1.Image = bit;
}
camera.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null || txtPath.Text.Equals(""))
{
MessageBox.Show("请先选择图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Bitmap map = new Bitmap(pictureBox1.Image);
Bitmap newMap = ImageHelper.KiLighten(map,10);
pictureBox1.Image = newMap;
}
private void button4_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null || txtPath.Text.Equals(""))
{
MessageBox.Show("请先选择图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Bitmap map = new Bitmap(pictureBox1.Image);
Bitmap newMap = ImageHelper.KiLighten(map, -10);
pictureBox1.Image = newMap;
}
private void cmbCodeType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCodeType.SelectedIndex >= 0)
{
txtParamPath.Text = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
}
}
}
}
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CodeLibrary;
namespace CodeLibrary
{
public partial class FrmCodeLearn : Form
{
public FrmCodeLearn()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
string filePath = txtParamPath.Text;
string cameraName = cmbCameraList.Text;
string codeType = this.cmbCodeType.Text;
int count = cmbCount.SelectedIndex + 1;
if (chbUseCamera.Checked)
{
if (cameraName.Equals(""))
{
MessageBox.Show("请选择摄像机", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
cameraName = "";
if (pictureBox1.Image == null)
{
MessageBox.Show("请先选择图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Bitmap bitmap = new Bitmap( pictureBox1.Image);
HObject Image = HDCodeHelper.Bitmap2HObjectBpp24(bitmap);
HDCodeLearnHelper.DefaultImage = Image;
}
Task.Factory.StartNew(delegate ()
{
HDCodeLearnHelper.StartLearn(this.hWindowControl1.HalconWindow, cameraName, codeType, filePath, count,5000);
});
FormStatus(true);
}
private void FormStatus(bool open)
{
btnOpen.Enabled = !open;
btnStop.Enabled = open;
}
private void btnStop_Click(object sender, EventArgs e)
{
HDCodeLearnHelper.StopLearn();
FormStatus(false);
}
private void FrmCamera_Load(object sender, EventArgs e)
{
cmbCount.SelectedIndex = 0;
chbTest.Checked = HDCodeLearnHelper.IsNeedTest;
CheckForIllegalCrossThreadCalls = false;
HDLogUtil.logBox = this.richTextBox2;
if (HDCodeLearnHelper.codeTypeList.Count <= 0)
{
HDCodeLearnHelper.LoadConfig("", "");
}
FormStatus(false);
cmbCameraList.DataSource = HDCodeLearnHelper.cameraNameList;
if (HDCodeLearnHelper.cameraNameList.Count > 0)
{
cmbCameraList.SelectedIndex = 0;
}
cmbCodeType.DataSource = HDCodeLearnHelper.codeTypeList;
if (HDCodeLearnHelper.codeTypeList.Count > 0)
{
cmbCodeType.SelectedIndex = 0;
}
string filePath =HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text);
txtParamPath.Text = filePath;
cmbCount.SelectedIndex = 0;
timer1.Start();
}
private void FrmCamera_FormClosed(object sender, FormClosedEventArgs e)
{
if (btnStop.Enabled.Equals(true))
{
btnStop_Click(null, null);
HDLogUtil.logBox = null;
FormStatus(false);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (HDCodeLearnHelper.IsRun)
{
if (btnOpen.Enabled)
{
btnOpen.Enabled = false ;
}
}
else
{
if (btnOpen.Enabled.Equals(false))
{
btnOpen.Enabled = true;
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void cmbCodeType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCodeType.SelectedIndex >= 0)
{
txtParamPath.Text = HDCodeHelper.GetCodeParamFilePath(cmbCodeType.Text );
}
}
private void btnClearLog_Click(object sender, EventArgs e)
{
HDLogUtil.ClearLog();
}
private void chbTest_CheckedChanged(object sender, EventArgs e)
{
HDCodeLearnHelper.IsNeedTest = chbTest.Checked;
}
private void btnSelImage_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Title = "选择二维码图片";
openDialog.Filter = "图片(*.jpg)|*.jpg|图片(*.png)|*.png|图片(*.bmp)|*.bmp";
//openDialog.DefaultExt = "png";
System.Windows.Forms.DialogResult result = openDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
txtPath.Text = openDialog.FileName;
string filename = txtPath.Text;
if (string.IsNullOrEmpty(filename))
{
MessageBox.Show("获取二维码图片为空");
}
pictureBox1.Image = null;
//读取图片内容
Image img = (Image)Image.FromFile(filename).Clone();
pictureBox1.Image = img;
}
private void txtPath_TextChanged(object sender, EventArgs e)
{
}
private void chbUseCamera_CheckedChanged(object sender, EventArgs e)
{
if (chbUseCamera.Checked)
{
cmbCameraList.Enabled = true ;
btnSelImage.Enabled = false;
}
else
{
cmbCameraList.Enabled = false ;
btnSelImage.Enabled = true ;
}
}
private void btnDelOld_Click(object sender, EventArgs e)
{
string path = txtParamPath.Text;
if (path.Equals(""))
{
return;
}
FileInfo file = new FileInfo(path);
DialogResult result = MessageBox.Show("确定删除文件:" +file.Name+ "", "确认删除", MessageBoxButtons.YesNo);
if (result.Equals(DialogResult.Yes))
{
File.Delete(path);
}
}
}
}
using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class HDLogUtil
{
private static string logName = "";
public static string LogName
{
get { return LogName; }
set
{
logName = value;
LOGGER = LogManager.GetLogger(LogName);
}
}
private static ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Dictionary<int, DateTime> lastErrorLogTime = new Dictionary<int, DateTime>();
public static System.Windows.Forms.RichTextBox logBox = null;
public static int showCount = 50;
public static bool debug_opened = false;
static HDLogUtil()
{
XmlConfigurator.Configure();
}
public static void info(string msg)
{
LOGGER.Info(LOGGER.Logger.Name + " - " + msg);
AddToBox(msg);
}
public static void debug(string msg)
{
LOGGER.Debug(LOGGER.Logger.Name + " - " + msg);
if (debug_opened)
{
AddToBox(msg);
}
}
public static void error(string errorMsg)
{
LOGGER.Error(LOGGER.Logger.Name + " - " + errorMsg);
AddToBox(errorMsg);
}
private static void AddToBox(string msg)
{
try
{
if (logBox == null)
{
return;
}
ShowLogPro(msg);
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.StackTrace);
}
}
private static int count = 0;
private static void ShowLogPro(string msg)
{
try
{
if (count > showCount)
{
count = 0;
logBox.Clear();
}
System.DateTime now = System.DateTime.Now;
logBox.AppendText(now.ToLongTimeString() + " " + msg + Environment.NewLine);
count++;
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.ToString());
}
}
public static void ClearLog()
{
if (logBox != null)
{
logBox.Text = "";
count = 0;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
public class ImageHelper
{ /// <summary>
/// 图像灰度化
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap ToGray(Bitmap bmp)
{
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
//利用公式计算灰度值
int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
Color newColor = Color.FromArgb(gray, gray, gray);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像灰度反转
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap GrayReverse(Bitmap bmp)
{
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
Color newColor = Color.FromArgb(255 - color.R, 255 - color.G, 255 - color.B);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static Bitmap ConvertTo1Bpp1(Bitmap bmp)
{
int average = 0;
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color color = bmp.GetPixel(i, j);
average += color.B;
}
}
average = (int)average / (bmp.Width * bmp.Height);
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
int value = 255 - color.B;
Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255, 255, 255);
bmp.SetPixel(i, j, newColor);
}
}
return bmp;
}
/// <summary>
/// 图像二值化2
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static Bitmap ConvertTo1Bpp2(Bitmap img)
{
int w = img.Width;
int h = img.Height;
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
for (int y = 0; y < h; y++)
{
byte[] scan = new byte[(w + 7) / 8];
for (int x = 0; x < w; x++)
{
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
}
return bmp;
}
/// <summary>
/// 图像明暗调整
/// </summary>
/// <param name="b">原始图</param>
/// <param name="degree">亮度[-255, 255]</param>
/// <returns></returns>
public static Bitmap KiLighten(Bitmap b, int degree)
{
if (b == null)
{
return null;
}
if (degree < -255) degree = -255;
if (degree > 255) degree = 255;
try
{
int width = b.Width;
int height = b.Height;
int pix = 0;
BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* p = (byte*)data.Scan0;
int offset = data.Stride - width * 3;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// 处理指定位置像素的亮度
for (int i = 0; i < 3; i++)
{
pix = p[i] + degree;
if (degree < 0) p[i] = (byte)Math.Max(0, pix);
if (degree > 0) p[i] = (byte)Math.Min(255, pix);
} // i
p += 3;
} // x
p += offset;
} // y
}
b.UnlockBits(data);
return b;
}
catch
{
return null;
}
} // end of Lighten
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CodeLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CodeLibrary")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("2e0d9598-cb37-46dc-9c9b-d36d4d344451")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.*")]
\ No newline at end of file \ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2043
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeTest", "CodeTest\CodeTest.csproj", "{780143A4-7A42-412B-8C70-FB77DCA9396D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Common\Common.csproj", "{43CDD09E-FCF3-4960-A01D-3BBFE9933122}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeLibrary", "CodeLibrary\CodeLibrary.csproj", "{2E0D9598-CB37-46DC-9C9B-D36D4D344451}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{780143A4-7A42-412B-8C70-FB77DCA9396D}.Release|Any CPU.Build.0 = Release|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.Build.0 = Release|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2E0D9598-CB37-46DC-9C9B-D36D4D344451}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {86EE028B-D15B-4A8A-ADC7-599806646D8C}
EndGlobalSection
EndGlobal

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2043
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeSplicing", "CodeSplicing\CodeSplicing.csproj", "{7C2222B4-E0D9-41FE-A5FF-09592344CE85}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7C2222B4-E0D9-41FE-A5FF-09592344CE85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7C2222B4-E0D9-41FE-A5FF-09592344CE85}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7C2222B4-E0D9-41FE-A5FF-09592344CE85}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7C2222B4-E0D9-41FE-A5FF-09592344CE85}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FAFC0A6D-D2BA-489E-8A17-62111D351D53}
EndGlobalSection
EndGlobal
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<appSettings>
<!--是否开机自动启动料仓-->
<add key="App_AutoRun" value="0"/>
<!--摄像机名称列表配置,用#分割-->
<!--<add key ="CameraName" value ="[0] Integrated Camera"/>-->
<add key="CameraName" value="tsavCamera"/>
<!--<add key ="CameraName" value ="codeCamera"/>-->
<!--二维码类型列表配置,用#分割-->
<add key="CodeType" value="Data Matrix ECC 200#QR Code"/>
<!--二维码参数文件所在路径,文件名与二维码类型名一样-->
<add key="CodeParamPath" value="\Conifg\"/>
<add key ="SplicingStrConfig" value ="RID*PN*MPN*QTY*DATE*LOT"/>
</appSettings>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs/SingleStore.log"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<datePattern value="yyyy-MM-dd"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%date][%t]%-5p %m%n"/>
</layout>
</appender>
<root>
<level value="Info"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>
using System;
using Basler.Pylon;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
namespace Asa
{
public class Basler_Pylon
{
/// <summary>
/// 当前相机
/// </summary>
private Camera cameraCur = null;
/// <summary>
/// 所有相机列表
/// </summary>
private List<ICameraInfo> cameraAll;
/// <summary>
/// 所有相机的名称
/// </summary>
private List<string> cameraName;
/// <summary>
/// 获取连续图像
/// </summary>
public delegate void GrabImageEvent();
/// <summary>
/// 获取连续图像事件,需要跨线程操作
/// </summary>
public event GrabImageEvent GrabImage;
public Basler_Pylon()
{
Load();
}
#region 属性
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
/// <summary>
/// 相机总数
/// </summary>
public int Count
{
get { return cameraAll == null ? 0 : cameraAll.Count; }
}
/// <summary>
/// 相机名称,ModelName,SerialNumber
/// </summary>
public string[] CameraName
{
get { return cameraName.ToArray(); }
}
/// <summary>
/// 当前相机是否打开
/// </summary>
public bool IsOpen
{
get
{
if (cameraCur == null)
return false;
else
return cameraCur.IsOpen;
}
}
/// <summary>
/// 相机图像宽度
/// </summary>
public int Width { set; get; }
/// <summary>
/// 相机图像高度
/// </summary>
public int Height { set; get; }
/// <summary>
/// 相机32位缓存
/// </summary>
public byte[] Buffer { get; private set; }
/// <summary>
/// 相机32位图像
/// </summary>
public Bitmap Image { get; private set; }
#endregion
#region 方法
public void Load()
{
cameraAll = CameraFinder.Enumerate();
cameraName = new List<string>();
foreach (ICameraInfo info in cameraAll)
cameraName.Add(info[CameraInfoKey.ModelName].ToString() + " (" + info[CameraInfoKey.SerialNumber].ToString() + ")");
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool Open(string name)
{
int n = cameraName.FindIndex(s => s == name);
if (n == -1)
return false;
else
return Open(n);
}
/// <summary>
/// 打开指定相机
/// </summary>
/// <param name="idx">索引</param>
/// <returns></returns>
public bool Open(int idx)
{
if (idx < 0 || idx >= cameraAll.Count) return false;
if (cameraCur != null) Close();
try
{
cameraCur = new Camera(cameraAll[idx]);
//cameraCur.ConnectionLost += OnConnectionLost;
//cameraCur.CameraOpened += OnCameraOpened;
//cameraCur.CameraClosed += OnCameraClosed;
//cameraCur.StreamGrabber.GrabStarted += OnGrabStarted;
cameraCur.StreamGrabber.ImageGrabbed += OnImageGrabbed;
//cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
cameraCur.Open();
Width = Convert.ToInt32(cameraCur.Parameters[PLCamera.Width].GetValue());
Height = Convert.ToInt32(cameraCur.Parameters[PLCamera.Height].GetValue());
cameraCur.Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1); //加载用户设置1
bool bln = cameraCur.Parameters[PLCamera.UserSetLoad].TryExecute(); //执行设置
return true;
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
}
/// <summary>
/// 关闭当前相机
/// </summary>
public void Close()
{
if (cameraCur != null)
{
cameraCur.Close();
cameraCur.Dispose();
cameraCur = null;
}
}
/// <summary>
/// 停止抓取数据
/// </summary>
public void Stop()
{
if (cameraCur != null)
cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取一张图像
/// </summary>
public void GrabOne()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
//cameraCur.StreamGrabber.Start();
//IGrabResult grabResult = cameraCur.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
IGrabResult grabResult = cameraCur.StreamGrabber.GrabOne(5000);
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
//cameraCur.StreamGrabber.Stop();
}
/// <summary>
/// 抓取连续图像,触发GrabImage事件
/// </summary>
public void GrabContinuous()
{
cameraCur.Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.Continuous);
cameraCur.StreamGrabber.Start(GrabStrategy.OneByOne, GrabLoop.ProvidedByStreamGrabber);
}
#endregion
private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
{
try
{
IGrabResult grabResult = e.GrabResult;
if (!grabResult.IsValid) return;
Image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = Image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
IntPtr ptrBmp = bmpData.Scan0;
int picSize = bmpData.Stride * grabResult.Height;
PixelDataConverter conv = new PixelDataConverter();
conv.OutputPixelFormat = PixelType.BGRA8packed;
conv.Convert(ptrBmp, picSize, grabResult);
Buffer = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(ptrBmp, Buffer, 0, picSize);
Image.UnlockBits(bmpData);
GrabImage?.Invoke();
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
finally
{
e.DisposeGrabResultIfClone();
}
}
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Asa
{
/// <summary>
/// 公共的
/// </summary>
public static class Common
{
/// <summary>
/// 设置文件的路径
/// </summary>
public static readonly string SET_FILE_PATH = System.IO.Directory.GetCurrentDirectory() + "\\Setting.xml";
/// <summary>
/// 模板文件的路径文件夹
/// </summary>
public static readonly string ITEM_DIR = System.IO.Directory.GetCurrentDirectory() + "\\Item\\";
/// <summary>
/// 日志文件的路径文件夹
/// </summary>
public static readonly string LOG_DIR = System.IO.Directory.GetCurrentDirectory() + "\\Log\\";
/// <summary>
/// 用于生成标签的路径文件夹
/// </summary>
public static readonly string LABEL_DIR = System.IO.Directory.GetCurrentDirectory() + "\\Label\\";
/// <summary>
/// 用于语言的路径文件夹
/// </summary>
public static readonly string LANGUAGE_DIR = System.IO.Directory.GetCurrentDirectory() + "\\Language\\";
public static Basler_Pylon Camera = new Basler_Pylon();
public static Template Template = new Template();
public static ConfigParam Config = new ConfigParam();
public static CodeLabel Label = new CodeLabel();
public static MultLang Language = new MultLang();
/// <summary>
/// 日志输出
/// </summary>
/// <param name="s"></param>
public static void LogOut(string s)
{
//if (!System.IO.Directory.Exists(LOG_DIR))
// System.IO.Directory.CreateDirectory(LOG_DIR);
//string path = LOG_DIR + string.Format("{0:yyyy_MM_dd}.txt", DateTime.Now);
//string contents = string.Format("{0:HH:mm:ss}->", DateTime.Now) + s + "\r\n";
//System.IO.File.AppendAllText(path, contents, System.Text.Encoding.UTF8);
}
/// <summary>
/// 日志输出
/// </summary>
/// <param name="rtx"></param>
/// <param name="s"></param>
public static void LogOut(System.Windows.Forms.RichTextBox rtx, string s)
{
rtx.AppendText(s + "\r\n");
LogOut(s);
}
}
/// <summary>
/// 配置
/// </summary>
public class ConfigParam
{
/// <summary>
/// 拼接需要用到的字段
/// </summary>
public List<string> Field = new List<string>();
/// <summary>
/// 拼接字符串的字符
/// </summary>
public string Chars = "";
/// <summary>
/// 起始,长度,当前
/// </summary>
public int[] RID;
/// <summary>
/// 默认打印机
/// </summary>
public string Printer;
/// <summary>
/// 本地打印机列表
/// </summary>
public List<string> PrinterList = new List<string>();
/// <summary>
/// 光源串口名
/// </summary>
public string LightPort;
/// <summary>
/// 所有本地串口
/// </summary>
public List<string> SerialPort = new List<string>();
public string LabelDefault;
public string TemplateDefault;
public string Language;
private XML xml;
/// <summary>
/// 初始化,读取设置
/// </summary>
public ConfigParam()
{
xml = new XML();
xml.Open(Common.SET_FILE_PATH);
Field.AddRange(xml.GetText("Field").Split(','));
Chars = xml.GetText("Chars");
Printer = xml.GetText("Printer");
LightPort = xml.GetText("Light");
LabelDefault = xml.GetText("Label");
TemplateDefault = xml.GetText("TempLate");
Language = xml.GetText("Language");
string[] s = xml.GetText("Rid").Split(',');
RID = new int[3];
RID[0] = Convert.ToInt32(s[0]);
RID[1] = Convert.ToInt32(s[1]);
RID[2] = Convert.ToInt32(s[2]);
foreach (string ss in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
PrinterList.Add(ss);
SerialPort.AddRange(System.IO.Ports.SerialPort.GetPortNames());
}
/// <summary>
/// 字段添加
/// </summary>
/// <param name="s"></param>
public void FieldAdd(string s)
{
Field.Add(s);
string f = string.Join(",", Field);
xml.SetText(f, "Field");
xml.Save();
}
/// <summary>
/// 字段删除
/// </summary>
/// <param name="idx"></param>
public void FieldDel(int idx)
{
Field.RemoveAt(idx);
string f = string.Join(",", Field);
xml.SetText(f, "Field");
xml.Save();
}
/// <summary>
/// rid字段更新
/// </summary>
public void UpdateRid()
{
xml.SetText(string.Join(",", RID), "Rid");
xml.Save();
}
public void UpdateLabel(string s)
{
xml.SetText(s, "Label");
xml.Save();
}
public void UpdateTemplate(string s)
{
xml.SetText(s, "Template");
xml.Save();
}
public void UpdateLanguage(string s)
{
xml.SetText(s, "Language");
Language = s;
xml.Save();
}
}
/// <summary>
/// 标签区域矩形
/// </summary>
public class AreaRect
{
/// <summary>
/// 中心点
/// </summary>
public PointF Center;
/// <summary>
/// 区域大小
/// </summary>
public SizeF Size;
/// <summary>
/// 旋转角度
/// </summary>
public float Angle;
/// <summary>
/// 区域点坐标
/// </summary>
public PointF[] Points;
/// <summary>
/// 文本
/// </summary>
public string Text;
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using HalconDotNet;
namespace Asa
{
public class Halcon
{
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
/// <summary>
/// 解读条形码
/// </summary>
/// <param name="bmp"></param>
/// <param name="codeInfo"></param>
/// <returns></returns>
public bool DecodeBarCode(Bitmap bmp, out List<BarCodeInfo> codeInfo)
{
HObject hObj = null;
codeInfo = new List<BarCodeInfo>();
//图像转成halcon的类型
try
{
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
HOperatorSet.GenImageInterleaved(out hObj, bmpData.Scan0, "bgrx", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
bmp.UnlockBits(bmpData);
}
catch (Exception ex)
{
hObj = null;
ErrInfo = ex.Message;
return false;
}
try
{
HOperatorSet.Rgb1ToGray(hObj, out HObject grayImage);
HOperatorSet.CreateBarCodeModel(new HTuple(), new HTuple(), out HTuple hv_BarCode); //创建条码模型
HOperatorSet.SetBarCodeParam(hv_BarCode, "num_scanlines", 5); //扫描线的最大数量
HOperatorSet.SetBarCodeParam(hv_BarCode, "min_identical_scanlines", 3); //成功解码最少扫描线数量
HOperatorSet.SetBarCodeParam(hv_BarCode, "start_stop_tolerance", "high"); //扫描线的起点和终点的容许误差
HOperatorSet.SetBarCodeParam(hv_BarCode, "max_diff_orient", 5); //条码相邻两条竖条边缘扭曲的最大角度容差
HOperatorSet.FindBarCode(grayImage, out HObject symbolRegions, hv_BarCode, "auto", out HTuple hv_String); //寻找条码
HOperatorSet.GetBarCodeResult(hv_BarCode, "all", "decoded_types", out HTuple hv_Type); //获取条码类型
HOperatorSet.GetBarCodeResult(hv_BarCode, "all", "orientation", out HTuple hv_Orientation); //获取条码方向,x轴逆时针[0,180],顺时针[0,-180]
HOperatorSet.AreaCenter(symbolRegions, out HTuple hv_Area, out HTuple hv_Row, out HTuple hv_Column); //获取面积中心点
HOperatorSet.RegionFeatures(symbolRegions, "width", out HTuple hv_width); //条形码宽度
HOperatorSet.RegionFeatures(symbolRegions, "height", out HTuple hv_height); //条形码高度
HOperatorSet.ClearBarCodeModel(hv_BarCode); //清除条码模型
//支持‘Data Matrix ECC 200’、‘QR Code’和‘PDF417’共3种类型
//‘standard_recognition’、‘enhanced_recognition’、‘maximum_recognition’
//HOperatorSet.CreateDataCode2dModel("QR Code", "default_parameters", "maximum_recognition", out HTuple dataCodeHandle);
//HOperatorSet.SetDataCode2dParam(dataCodeHandle, "timeout", 200); //一个二维码的解码时间
//HOperatorSet.SetDataCode2dParam(dataCodeHandle, "symbol_size_min", 16); //码粒最小个数
//HOperatorSet.SetDataCode2dParam(dataCodeHandle, "symbol_size_max", 30); //码粒最大个数
//HOperatorSet.SetDataCode2dParam(dataCodeHandle, "module_size_min", 10); //码粒最小像素
//HOperatorSet.SetDataCode2dParam(dataCodeHandle, "module_size_max", 30); //码粒最大像素
//HOperatorSet.FindDataCode2d(grayImage, out HObject symbolXLDs, dataCodeHandle, new HTuple(), new HTuple(), out HTuple resultHandles, out HTuple decodedDataStrings);
//HOperatorSet.ClearDataCode2dModel(dataCodeHandle);
int n = hv_String.SArr.Length;
for (int i = 0; i < n; i++)
{
BarCodeInfo info = new BarCodeInfo();
info.centerX = Convert.ToSingle(hv_Column.DArr[i]);
info.centerY = Convert.ToSingle(hv_Row.DArr[i]);
info.text = hv_String.SArr[i];
info.angle = Convert.ToSingle(hv_Orientation.DArr[i]);
codeInfo.Add(info);
}
return true;
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
}
}
/// <summary>
/// 一维条码信息
/// </summary>
public struct BarCodeInfo
{
/// <summary>
/// 文本
/// </summary>
public string text;
/// <summary>
/// 中心点x
/// </summary>
public float centerX;
/// <summary>
/// 中心点y
/// </summary>
public float centerY;
/// <summary>
/// 角度,3点钟方向0°,逆时针为正,顺时针为负。
/// </summary>
public float angle;
/// <summary>
/// 条码矩形的4个顶点
/// </summary>
public PointF[] peak;
public BarCodeInfo(string s)
{
string[] ss = s.Split(',');
centerX = Convert.ToSingle(ss[0]);
centerY = Convert.ToSingle(ss[1]);
angle = Convert.ToSingle(ss[2]);
text = ss[3];
peak = new PointF[4];
}
public BarCodeInfo(string text, float centerX, float centerY, float angle)
{
this.text = text;
this.centerX = centerX;
this.centerY = centerY;
this.angle = angle;
peak = new PointF[4];
}
public string GetString()
{
return centerX + "," + centerY + "," + angle + "," + text;
}
public void SetString(string s)
{
string[] ss = s.Split(',');
centerX = Convert.ToSingle(ss[0]);
centerY = Convert.ToSingle(ss[1]);
angle = Convert.ToSingle(ss[2]);
text = ss[3];
}
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
namespace Asa
{
public class ImageZoom
{
public PointF offset = new PointF(0, 0);
private List<PointF[]> polygon = new List<PointF[]>();
private List<PointF> center = new List<PointF>();
private List<string> text = new List<string>();
private PictureBox pic;
private Bitmap bmp;
private Button btn_small;
private Button btn_large;
private Point oldPoint = new Point(0, 0);
private PointF oldOffset = new PointF(0, 0);
/// <summary>
/// 判断鼠标按下,(用于避免bug,双击打开对话框的文件,会触发底下的picturebox的mousemove事件)
/// </summary>
private bool down = false;
private float oldZoom = 0;
private int zoomIdx = -1;
private const int BUTTON_SIZE = 50;
private readonly Color BUTTON_BACK = Color.FromArgb(128, 255, 255, 255); //背景
private readonly Color BUTTON_OVER = Color.FromArgb(128, 192, 255, 192); //经过
private readonly Color BUTTON_DOWN = Color.FromArgb(128, 255, 255, 192); //按下
private const float ZOOM_MAX = 2f;
private const float ZOOM_MIN = 0.1f;
private const float ZOOM_PRECISE = 0.05f;
private readonly float[] ZOOM_SCALE = new float[] { 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f };
public ImageZoom()
{
ZoomIdx = 1;
ImageMove = true;
}
/// <summary>
/// 用于显示的控件
/// </summary>
public PictureBox ShowControl
{
set
{
pic = value;
pic.Paint += Pic_Paint;
pic.Resize += Pic_Resize;
pic.MouseWheel += Pic_MouseWheel;
pic.MouseMove += Pic_MouseMove;
pic.MouseUp += Pic_MouseUp;
pic.MouseDown += Pic_MouseDown;
btn_small = new Button();
btn_small.BackColor = BUTTON_BACK;
btn_small.Text = "-";
btn_small.Font = new Font("宋体", 38f);
btn_small.TextAlign = ContentAlignment.MiddleCenter;
btn_small.Size = new Size(BUTTON_SIZE, BUTTON_SIZE);
btn_small.Location = new Point(pic.ClientSize.Width - BUTTON_SIZE, pic.ClientSize.Height - BUTTON_SIZE);
btn_small.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
btn_small.FlatStyle = FlatStyle.Flat;
btn_small.FlatAppearance.BorderSize = 0;
btn_small.FlatAppearance.MouseOverBackColor = BUTTON_OVER;
btn_small.FlatAppearance.MouseDownBackColor = BUTTON_DOWN;
btn_small.Click += Btn_small_Click;
pic.Controls.Add(btn_small);
btn_large = new Button();
btn_large.BackColor = BUTTON_BACK;
btn_large.Text = "+";
btn_large.Font = new Font("宋体", 38f);
btn_large.TextAlign = ContentAlignment.MiddleCenter;
btn_large.Size = new Size(BUTTON_SIZE, BUTTON_SIZE);
btn_large.Location = new Point(pic.ClientSize.Width - BUTTON_SIZE - BUTTON_SIZE, pic.ClientSize.Height - BUTTON_SIZE);
btn_large.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
btn_large.FlatStyle = FlatStyle.Flat;
btn_large.FlatAppearance.BorderSize = 0;
btn_large.FlatAppearance.MouseOverBackColor = BUTTON_OVER;
btn_large.FlatAppearance.MouseDownBackColor = BUTTON_DOWN;
btn_large.Click += Btn_large_Click;
pic.Controls.Add(btn_large);
}
}
/// <summary>
/// 图像移动
/// </summary>
public bool ImageMove { set; get; }
/// <summary>
/// 自动缩放比例
/// </summary>
public bool AutoZoom { set; get; }
/// <summary>
/// 缩放比例
/// </summary>
public float Zoom { private set; get; }
public int ZoomIdx
{
set
{
if (value < 0)
zoomIdx = 0;
else if (value > ZOOM_SCALE.Length - 1)
zoomIdx = ZOOM_SCALE.Length - 1;
else
zoomIdx = value;
Zoom = ZOOM_SCALE[ZoomIdx];
oldZoom = Zoom;
}
get
{
return zoomIdx;
}
}
public void Update()
{
if (bmp == null) return;
if (AutoZoom)
{
float f1 = pic.Width / (float)bmp.Width;
float f2 = pic.Height / (float)bmp.Height;
Zoom = Math.Min(f1, f2);
}
pic.Refresh();
}
public void Update(Bitmap bmp)
{
//drawRect = new Rectangle();
this.bmp = bmp;
if (AutoZoom)
{
float f1 = pic.Width / (float)bmp.Width;
float f2 = pic.Height / (float)bmp.Height;
oldZoom = Zoom = Math.Min(f1, f2);
}
polygon.Clear();
pic.Refresh();
}
public string[] ZoomName()
{
string[] rtn = new string[ZOOM_SCALE.Length];
for (int i = 0; i < rtn.Length; i++)
rtn[i] = Convert.ToInt32(ZOOM_SCALE[i] * 100) + "%";
return rtn;
}
/// <summary>
/// 添加轮廓
/// </summary>
/// <param name="pt"></param>
/// <param name="center"></param>
/// <param name="text"></param>
public void AddOutline(PointF[] pt, PointF center, string text)
{
polygon.Add(pt);
this.center.Add(center);
this.text.Add(text);
}
public void ClearOutline()
{
polygon.Clear();
center.Clear();
text.Clear();
}
private void Btn_large_Click(object sender, EventArgs e)
{
oldZoom = Zoom;
if (Zoom < ZOOM_MAX) Zoom += ZOOM_PRECISE;
float w1 = (bmp.Width * Zoom - bmp.Width * oldZoom) / 2;
offset.X -= w1;
w1 = (bmp.Height * Zoom - bmp.Height * oldZoom) / 2;
offset.Y -= w1;
pic.Refresh();
}
private void Btn_small_Click(object sender, EventArgs e)
{
oldZoom = Zoom;
if (Zoom > ZOOM_MIN) Zoom -= ZOOM_PRECISE;
float w1 = (bmp.Width * Zoom - bmp.Width * oldZoom) / 2;
offset.X -= w1;
w1 = (bmp.Height * Zoom - bmp.Height * oldZoom) / 2;
offset.Y -= w1;
pic.Refresh();
}
private void Pic_Paint(object sender, PaintEventArgs e)
{
if (bmp == null) return;
RectangleF destRect = new RectangleF(offset.X, offset.Y, bmp.Width * Zoom, bmp.Height * Zoom);
RectangleF srcRect = new RectangleF(0, 0, bmp.Width, bmp.Height);
e.Graphics.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel);
for (int i = 0; i < polygon.Count; i++)
{
float x = offset.X + center[i].X * Zoom;
float y = offset.Y + center[i].Y * Zoom;
PointF[] points = new PointF[polygon[i].Length];
RectangleF re = new RectangleF(x - 20, y - 20, 40, 40);
Font f = new Font("宋体", 12f, FontStyle.Bold);
SizeF sizeF = e.Graphics.MeasureString(text[i], f);
for (int j = 0; j < points.Length; j++)
{
points[j].X = offset.X + polygon[i][j].X * Zoom;
points[j].Y = offset.Y + polygon[i][j].Y * Zoom;
}
e.Graphics.DrawPolygon(Pens.Red, points);
if (text[i] == null) continue;
SolidBrush brush = new SolidBrush(Color.FromArgb(150, 255, 255, 0));
e.Graphics.FillEllipse(brush, re);
e.Graphics.DrawString(text[i], f, Brushes.Red, x - sizeF.Width / 2, y - sizeF.Height / 2);
}
}
private void Pic_Resize(object sender, EventArgs e)
{
if (AutoZoom) Update();
}
private void Pic_MouseWheel(object sender, MouseEventArgs e)
{
if (AutoZoom) return;
oldZoom = Zoom;
if (e.Delta > 0)
{
if (Zoom < ZOOM_MAX) Zoom += ZOOM_PRECISE;
}
else
{
if (Zoom > ZOOM_MIN) Zoom -= ZOOM_PRECISE;
}
float w1 = (e.X - offset.X) * (bmp.Width * Zoom) / (bmp.Width * oldZoom);
offset.X = e.X - w1;
w1 = (e.Y - offset.Y) * (bmp.Height * Zoom) / (bmp.Height * oldZoom);
offset.Y = e.Y - w1;
pic.Refresh();
}
private void Pic_MouseMove(object sender, MouseEventArgs e)
{
if (!down) return;
if (ImageMove && e.Button == MouseButtons.Left)
{
offset.X = e.X - oldPoint.X + oldOffset.X;
offset.Y = e.Y - oldPoint.Y + oldOffset.Y;
pic.Refresh();
}
}
private void Pic_MouseUp(object sender, MouseEventArgs e)
{
down = false;
}
private void Pic_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right)
{
down = true;
oldPoint = e.Location;
oldOffset = offset;
}
}
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Xml;
namespace Asa
{
/// <summary>
/// 多国语言
/// </summary>
public class MultLang
{
private bool needSave;
private XmlDocument xDoc;
private XmlNode xRoot, xNode;
private XmlNamespaceManager nsmgr;
private List<string> file = new List<string>();
private List<string> name = new List<string>();
/// <summary>
/// 多国语言
/// </summary>
public MultLang()
{
//新建文件夹
if (!System.IO.Directory.Exists(Common.LANGUAGE_DIR))
System.IO.Directory.CreateDirectory(Common.LANGUAGE_DIR);
//获取所有文件
xDoc = new XmlDocument();
file.AddRange(System.IO.Directory.GetFiles(Common.LANGUAGE_DIR, "*.xml"));
foreach (string s in file)
{
try
{
xDoc.Load(s);
xRoot = xDoc.LastChild;
name.Add(((XmlElement)xRoot).GetAttribute("Name"));
}
catch (Exception ex)
{
ErrInfo = ex.Message;
}
}
Index = 0;
if (file.Count == 0) Index = -1;
}
//====================属性====================
/// <summary>
/// 语言名称
/// </summary>
public string[] Name { get { return name.ToArray(); } }
/// <summary>
/// 语言总数
/// </summary>
public int Count { get { return file.Count; } }
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { get; set; }
/// <summary>
/// 索引
/// </summary>
public int Index { get; set; }
//====================公共方法====================
/// <summary>
/// 加载语言
/// </summary>
/// <param name="frm">窗口</param>
public void SetLanguage(Form frm)
{
if (frm == null) return;
Open();
xNode = xRoot;
if (xRoot == null) return;
SetLang(frm);
if (needSave) xDoc.Save(file[Index]);
needSave = false;
}
/// <summary>
/// 根据名称设置索引
/// </summary>
/// <param name="s"></param>
public void SetIndex(string s)
{
int n = name.FindIndex(t => t == s);
if (n > -1) Index = n;
}
/// <summary>
/// 获取对话框的列表
/// </summary>
/// <param name="formName"></param>
/// <returns></returns>
public List<string[]> GetDialog(string formName)
{
Open();
if (xRoot == null) return null;
xNode = xRoot.SelectSingleNode(formName, nsmgr);
if (xNode == null) return null;
XmlNode curr = xNode.SelectSingleNode("Dialog", nsmgr);
if (curr == null)
{
xNode.AppendChild(xDoc.CreateElement("Dialog"));
curr = xNode.SelectSingleNode("Dialog", nsmgr);
needSave = true;
}
XmlNodeList list = curr.ChildNodes;
List<string[]> rtn = new List<string[]>();
for (int i = 0; i < list.Count; i++)
{
string[] s = new string[2];
s[0] = list[i].Name;
s[1] = list[i].InnerText;
rtn.Add(s);
}
if (needSave) xDoc.Save(file[Index]);
needSave = false;
return rtn;
}
//====================私有方法====================
/// <summary>
/// 打开文件
/// </summary>
private void Open()
{
if (Index < 0 || Index >= file.Count) return;
xDoc.Load(file[Index]);
xRoot = xDoc.LastChild;
if (xRoot == null) return;
XmlNodeList list = xRoot.SelectNodes("//*");
nsmgr = new XmlNamespaceManager(xDoc.NameTable);
foreach (XmlNode n in list)
{
if (n.Prefix.Length > 0)
nsmgr.AddNamespace(n.Prefix, n.NamespaceURI);
}
}
/// <summary>
/// 转换字体
/// </summary>
/// <param name="s">格式:字体,字号,粗体,斜体</param>
/// <returns></returns>
private System.Drawing.Font ConvFont(string s)
{
string[] t = s.Split(',');
float emSize = Convert.ToSingle(t[1]);
System.Drawing.FontStyle style = System.Drawing.FontStyle.Regular;
if (t[2] == "B") style |= System.Drawing.FontStyle.Bold;
if (t[3] == "I") style |= System.Drawing.FontStyle.Italic;
System.Drawing.Font font = new System.Drawing.Font(t[0], emSize, style);
return font;
}
/// <summary>
/// 设置语言
/// </summary>
/// <param name="list"></param>
private void SetLang(Control list)
{
bool bln;
if (list.Name == "") return;
XmlNode curr = xNode.SelectSingleNode(list.Name, nsmgr);
if (curr == null)
{
xNode.AppendChild(xDoc.CreateElement(list.Name));
curr = xNode.SelectSingleNode(list.Name, nsmgr);
needSave = true;
}
else
{
bln = ((XmlElement)curr).HasAttribute("Text");
if (bln) list.Text = ((XmlElement)curr).GetAttribute("Text");
}
foreach (Control ctl in list.Controls)
{
if (ctl.Controls.Count > 0)
{
xNode = curr;
SetLang(ctl);
}
else
{
if (ctl.Name == "") continue;
XmlNode temp = curr.SelectSingleNode(ctl.Name, nsmgr);
if (temp == null)
{
curr.AppendChild(xDoc.CreateElement(ctl.Name));
temp = curr.SelectSingleNode(ctl.Name, nsmgr);
needSave = true;
}
else
{
bln = ((XmlElement)temp).HasAttribute("Text");
if (bln) ctl.Text = ((XmlElement)temp).GetAttribute("Text");
bln = ((XmlElement)temp).HasAttribute("Tag");
if (bln) ctl.Tag = ((XmlElement)temp).GetAttribute("Tag");
bln = ((XmlElement)temp).HasAttribute("Font");
if (bln) list.Font = ConvFont(((XmlElement)temp).GetAttribute("Font"));
}
}
}
}
}
}
\ No newline at end of file \ No newline at end of file
using OpenCvSharp;
using System;
using System.Drawing;
using System.Collections.Generic;
namespace Asa
{
public class OpenCV
{
/// <summary>
/// 提取矩形轮廓
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public List<AreaRect> extractRect(Bitmap bmp)
{
Mat src = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
Mat gray = src.CvtColor(ColorConversionCodes.BGR2GRAY, 1);
Cv2.PyrDown(gray, gray); //模糊
//Cv2.PyrDown(src, src);
//Cv2.MedianBlur(gray, gray, 3); //中值滤波
//Cv2.Threshold(gray, gray, 200, 255, ThresholdTypes.Tozero);
//Cv2.NamedWindow("qqq", WindowMode.Normal);
//gray.PyrDown();
//Cv2.ImShow("qqq", gray);
//Cv2.Sobel(gray, gray, MatType.CV_16S, 0, 1);
//Cv2.Sobel(gray, gray, MatType.CV_16S, 1, 0);
Cv2.Canny(gray, gray, 20, 128); //边缘 20,128
//ShowImg("canny", gray);
Mat[] contours = null;
Mat hierarchy = new Mat();
Cv2.FindContours(gray, out contours, hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple); //寻找轮廓
List<AreaRect> rtn = new List<AreaRect>();
bool repeat = false;
for (int index = 0; index < contours.Length; index++)
{
RotatedRect rect = Cv2.MinAreaRect(contours[index]);
//去除过大过小的矩形
if (rect.Size.Height < 100 || rect.Size.Width < 100) continue;
if (rect.Size.Height > bmp.Height / 3 || rect.Size.Width > bmp.Width / 3) continue;
AreaRect ar = new AreaRect();
ar.Center = new PointF(rect.Center.X * 2, rect.Center.Y * 2);
ar.Size = new SizeF(rect.Size.Width, rect.Size.Height);
ar.Angle = rect.Angle;
Point2f[] pf = rect.Points();
ar.Points = new PointF[pf.Length];
for (int i = 0; i < pf.Length; i++)
ar.Points[i] = new PointF(pf[i].X * 2, pf[i].Y * 2);
//找重复
repeat = false;
for (int i = 0; i < rtn.Count; i++)
{
if (Math.Abs(ar.Center.X - rtn[i].Center.X) < 10 &&
Math.Abs(ar.Center.Y - rtn[i].Center.Y) < 10 &&
Math.Abs(ar.Size.Width - rtn[i].Size.Width) < 10 &&
Math.Abs(ar.Size.Height - rtn[i].Size.Height) < 10 &&
Math.Abs(ar.Angle - rtn[i].Angle) < 5
)
{
repeat = true;
continue;
}
}
if (!repeat) rtn.Add(ar);
}
return rtn;
//Cv2.GetRotationMatrix2D()
}
//public class faadfsadf
//{
// public void extractRec(string imagePath)
// {
// Mat src = new Mat(imagePath, ImreadModes.GrayScale);
// Mat originalImg = new Mat(imagePath, ImreadModes.AnyColor);
// Cv2.PyrDown(src, src); //模糊
// Cv2.PyrDown(originalImg, originalImg);
// Cv2.MedianBlur(src, src, 3); //中值滤波
// //Cv2.Threshold(src, src, 50, 255, ThresholdTypes.BinaryInv);
// Cv2.Canny(src, src, 20, 128); //边缘
// ShowImg("canny", src);
// Mat[] contours = null;
// Mat hierarchy = new Mat();
// Cv2.FindContours(src, out contours, hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); //寻找轮廓
// //Mat linePic = Mat.Zeros(src.Rows, src.Cols, MatType.CV_8UC3);
// int contoursSize = contours.Length;
// int n = 0;
// for (int index = 0; index < contoursSize; index++)
// {
// //Cv2.DrawContours(linePic, contours, index, Scalar.RandomColor());
// //找出完整包含轮廓的最小矩形
// //Rect rect = Cv2.BoundingRect(contours[index]);
// RotatedRect rect = Cv2.MinAreaRect(contours[index]);
// if (rect.Size.Height < 100 || rect.Size.Width < 100)
// {
// continue;
// }
// //Cv2.Rectangle(originalImg, rect, Scalar.Red);
// Point2f[] pf = rect.Points();
// Point[] ps = new Point[pf.Length];
// for (int i = 0; i < pf.Length; i++)
// {
// ps[i] = new Point(pf[i].X, pf[i].Y);
// }
// Cv2.Line(originalImg, ps[0], ps[1], Scalar.Red);
// Cv2.Line(originalImg, ps[1], ps[2], Scalar.Red);
// Cv2.Line(originalImg, ps[2], ps[3], Scalar.Red);
// Cv2.Line(originalImg, ps[3], ps[0], Scalar.Red);
// n++;
// }
// ShowImg("Line", originalImg);
// return;
// Mat[] polyContours = new Mat[contoursSize];
// double maxArea = 0;
// int maxAreaIndex = 0;
// for (int index = 0; index < contoursSize; index++)
// {
// Mat contour = contours[index];
// double currentArea = Cv2.ContourArea(contour);
// if (currentArea > maxArea)
// {
// maxAreaIndex = index;
// maxArea = currentArea;
// }
// Mat polyMat = Mat.Zeros(src.Size(), MatType.CV_8UC3);
// Cv2.ApproxPolyDP(contour, polyMat, 10, true);
// polyContours[index] = polyMat;
// Rect rect = Cv2.BoundingRect(polyContours[index]);
// originalImg.Rectangle(rect, Scalar.Red);
// //if (approx.size() == 4 &&
// // fabs(contourArea(Mat(approx))) > 1000 &&
// // isContourConvex(Mat(approx)))
// //{
// // double maxCosine = 0;
// // for (int j = 2; j < 5; j++)
// // {
// // double cosine = fabs(angle(approx[j % 4], approx[j - 2], approx[j - 1]));
// // maxCosine = MAX(maxCosine, cosine);
// // }
// // if (maxCosine < 0.3)
// // squares.push_back(approx);
// //}
// }
// //Mat polyPic = Mat.Zeros(src.Size(),MatType.CV_32SC2);
// //Cv2.DrawContours(polyPic, polyContours,maxAreaIndex,Scalar.Red);
// //Cv2.DrawContours(dst, polyContours, maxAreaIndex, Scalar.Red,2);
// Rect rec = Cv2.BoundingRect(polyContours[maxAreaIndex]);
// //originalImg.Rectangle(rec, Scalar.Red) ;
// ShowImg("Rec", originalImg);
// //originalImg.Rectangle(new Rect(rec.X* 2, rec.Y* 2, rec.Width * 2, rec.Height *2), Scalar.Red);
// //投影变换
// Point2f[] srcPoints = new Point2f[4];
// //左上,右上,右下,左下
// srcPoints[0] = new Point2f(rec.TopLeft.X * 2, rec.TopLeft.Y * 2);
// srcPoints[1] = new Point2f(rec.Right * 2, rec.Top * 2);
// srcPoints[2] = new Point2f(rec.BottomRight.X * 2, rec.BottomRight.Y * 2);
// srcPoints[3] = new Point2f(rec.Left * 2, rec.Bottom * 2);
// Point2f[] dstPoints = new Point2f[4];
// dstPoints[0] = new Point2f(0, 0);
// dstPoints[1] = new Point2f(rec.Width * 2, 0);
// dstPoints[2] = new Point2f(rec.Width * 2, rec.Height * 2);
// dstPoints[3] = new Point2f(0, rec.Height * 2);
// Mat transMat = Cv2.GetPerspectiveTransform(srcPoints, dstPoints); //得到变换矩阵
// Mat outPutImg = Mat.Zeros(new Size(rec.Width * 2, rec.Height * 2), MatType.CV_16UC1);
// Cv2.WarpPerspective(originalImg, outPutImg, transMat, outPutImg.Size()); //进行坐标变换
// Cv2.ImShow("Show Img", outPutImg);
// }
private void ShowImg(string winName, Mat img)
{
Cv2.NamedWindow(winName, WindowMode.Normal);
img.PyrDown();
Cv2.ImShow(winName, img);
//if (img.Width > 3800)
//{
// Rect roi = new Rect(1000, 1000, 800, 800);
// // 复制图像
// //Mat roiImg = new Mat(img, roi);
// Cv2.ImShow(winName, roiImg);
//}
//else
//{Cv2.ImShow(winName, img);
//}
}
//}
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Xml;
namespace Asa
{
public class XML
{
private XmlDocument xDoc;
private XmlNode xRoot;
private XmlNode xNode;
private XmlNode xNodeTemp;
private XmlNamespaceManager nsmgr;
private string path;
public XML()
{
xDoc = new XmlDocument();
nsmgr = new XmlNamespaceManager(xDoc.NameTable);
}
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { set; get; }
/// <summary>
/// 打开文档
/// </summary>
/// <param name="filePath">路径</param>
/// <returns></returns>
public bool Open(string filePath)
{
try
{
path = filePath;
xDoc.Load(filePath);
xNode = xRoot = xDoc.LastChild;
XmlNodeList list = xRoot.SelectNodes("//*");
foreach (XmlNode n in list)
{
if (n.Prefix.Length > 0)
nsmgr.AddNamespace(n.Prefix, n.NamespaceURI);
}
return true;
}
catch (Exception ex)
{
ErrInfo = ex.Message;
return false;
}
}
/// <summary>
/// 保存
/// </summary>
/// <returns></returns>
public bool Save()
{
if (path == null) return false;
try
{
xDoc.Save(path);
return true;
}
catch(Exception ex)
{
ErrInfo = ex.Message;
return false;
}
}
public void SetRoot()
{
xNode = xRoot;
}
public bool SetNode(string path)
{
xNode = xNode.SelectSingleNode(path, nsmgr);
return xNode != null;
}
public void SetNodeAdd(string path)
{
xNodeTemp = xNode.SelectSingleNode(path, nsmgr);
if (xNodeTemp == null)
{
xNode.AppendChild(xDoc.CreateElement(path));
Save();
xNode = xNode.SelectSingleNode(path, nsmgr);
}
else
{
xNode = xNodeTemp;
}
}
public void SelectNode(string path = null)
{
if (path == null)
xNode = xRoot;
else
xNode = xNode.SelectSingleNode(path, nsmgr);
}
public void SelectNode(int index, string path = null)
{
if (path == null)
xNode = xRoot.ChildNodes[index];
else
xNode = xNode.SelectSingleNode(path, nsmgr).ChildNodes[index];
}
/// <summary>
/// 选中Node,如果不存在就添加
/// </summary>
/// <param name="path"></param>
public void SelectAddNode(string path)
{
xNode = xNode.SelectSingleNode(path, nsmgr);
if (xNode == null)
{
xRoot.AppendChild(xDoc.CreateElement(path));
Save();
}
xNode = xRoot.SelectSingleNode(path, nsmgr);
}
/// <summary>
/// 获取节点属性
/// </summary>
/// <param name="name">属性名称</param>
/// <param name="path">路径</param>
/// <returns></returns>
public string GetAttribute(string name, string path = null)
{
if (path == null)
return ((XmlElement)xNode).GetAttribute(name);
else
return ((XmlElement)xNode.SelectSingleNode(path, nsmgr)).GetAttribute(name);
}
/// <summary>
/// 获取节点属性
/// </summary>
/// <param name="name">属性名称</param>
/// <param name="index">索引</param>
/// <param name="path">路径</param>
/// <returns></returns>
public string GetAttribute(string name, int index, string path = null)
{
if (path == null)
return ((XmlElement)xNode.ChildNodes[index]).GetAttribute(name);
else
return ((XmlElement)xNode.SelectSingleNode(path, nsmgr).ChildNodes[index]).GetAttribute(name);
}
/// <summary>
/// 获取节点文本
/// </summary>
/// <param name="text">文本</param>
/// <param name="path">路径</param>
public string GetText(string path = null)
{
if (path == null)
return xNode.InnerText;
else
{
XmlNode n = xNode.SelectSingleNode(path, nsmgr);
if (n == null)
return "";
else
return n.InnerText;
}
}
public int GetCount(string path = null)
{
if (path == null)
return xNode.ChildNodes.Count;
else
{
XmlNode n = xNode.SelectSingleNode(path, nsmgr);
if (n == null)
return 0;
else
return n.ChildNodes.Count;
}
}
/// <summary>
/// 设置节点文本
/// </summary>
/// <param name="text">文本</param>
/// <param name="path">路径</param>
public void SetText(string text, string path = null)
{
if (path == null)
xNode.InnerText = text;
else
xNode.SelectSingleNode(path, nsmgr).InnerText = text;
}
public void SetAttribute(string name, string value, string path = null)
{
if (path == null)
((XmlElement)xNode).SetAttribute(name, value);
else
((XmlElement)xNode.SelectSingleNode(path, nsmgr)).SetAttribute(name, value);
}
public void SetAttribute(string name, string value, int index, string path = null)
{
if (path == null)
((XmlElement)xNode.ChildNodes[index]).SetAttribute(name, value);
else
((XmlElement)xNode.SelectSingleNode(path, nsmgr).ChildNodes[index]).SetAttribute(name, value);
}
public void AddNode(string name, string path = null)
{
if (path == null)
xNode.AppendChild(xDoc.CreateElement(name));
else
xNode.SelectSingleNode(path, nsmgr).AppendChild(xDoc.CreateElement(name));
}
public void DelChildNode(string path = null)
{
if (path == null)
xNode.RemoveAll();
else
xNode.SelectSingleNode(path, nsmgr).RemoveAll();
}
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Drawing;
using ZXing;
using ZXing.Common;
using ZXing.Datamatrix;
namespace Asa
{
public class ZXingCode
{
public bool DecodeQRCode(Bitmap bmp, out string text)
{
DecodingOptions option = new DecodingOptions();
//option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE, BarcodeFormat.All_1D };
option.PossibleFormats = new List<BarcodeFormat>() { BarcodeFormat.QR_CODE };
BarcodeReader br = new BarcodeReader();
br.Options = option;
Result rs = br.Decode(bmp);
if (rs == null)
{
text = "";
return false;
}
else
{
text = rs.Text;
return true;
}
}
/// <summary>
/// DataMatrix矩阵二维码
/// </summary>
/// <param name="text"></param>
/// <param name="size"></param>
/// <returns></returns>
public Bitmap DataMatrix(string text, int size)
{
if (size < 10) size = 10;
//DatamatrixEncodingOptions dmxoption = new DatamatrixEncodingOptions();
//dmxoption.Height = size;
//dmxoption.Width = size;
//dmxoption.Margin = 10;
//dmxoption.PureBarcode = false;
//dmxoption.SymbolShape = ZXing.Datamatrix.Encoder.SymbolShapeHint.FORCE_NONE;
//BarcodeWriter barcodewriter = new BarcodeWriter();
//barcodewriter.Options = dmxoption;
//barcodewriter.Format = BarcodeFormat.DATA_MATRIX;
//return barcodewriter.Write(text);
DataMatrix.net.DmtxImageEncoderOptions opt = new DataMatrix.net.DmtxImageEncoderOptions();
opt.ModuleSize = size;
opt.MarginSize = 5;
DataMatrix.net.DmtxImageEncoder encoder = new DataMatrix.net.DmtxImageEncoder();
Bitmap bm = encoder.EncodeImage(text, opt);
return bm;
}
}
}
\ No newline at end of file \ No newline at end of file
using DataMatrix.net;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
namespace CodeSplicing
{
public class CodeCreate
{
//生成二维码图片的函数
public static Bitmap DMCode(string msg, int codeSizeInPixels, int margin = 5)
{
if (codeSizeInPixels <= 0)
{
codeSizeInPixels = 10;
}
DmtxImageEncoderOptions opt = new DmtxImageEncoderOptions();
opt.ModuleSize = codeSizeInPixels;
opt.MarginSize = margin;
DmtxImageEncoder encoder = new DmtxImageEncoder();
Bitmap bm = encoder.EncodeImage(msg, opt);
return bm;
}
public static Bitmap ZXingCode(string msg, int codeSizeInPixels, BarcodeFormat type)
{
if (codeSizeInPixels <= 0)
{
codeSizeInPixels = 10;
}
BarcodeWriter writer = new BarcodeWriter();
writer.Format = type;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options.DisableECI = true;
//设置内容编码
options.CharacterSet = "UTF-8";
//设置二维码的宽度和高度
options.Width = codeSizeInPixels;
options.Height = codeSizeInPixels;
//设置二维码的边距,单位不是固定像素
options.Margin = 1;
writer.Options = options;
Bitmap map = writer.Write(msg);
return map;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{7C2222B4-E0D9-41FE-A5FF-09592344CE85}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>CodeSplicing</RootNamespace>
<AssemblyName>CodeSplicing</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>1</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="Basler.Pylon, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e389355f398382ab, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\Basler.Pylon.dll</HintPath>
</Reference>
<Reference Include="CodeLibrary">
<HintPath>..\dll\CodeLibrary.dll</HintPath>
</Reference>
<Reference Include="DataMatrix.net">
<HintPath>..\dll\DataMatrix.net.dll</HintPath>
</Reference>
<Reference Include="halcondotnet, Version=12.0.0.0, Culture=neutral, PublicKeyToken=4973bed59ddbf2b8, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\dll\halcondotnet.dll</HintPath>
</Reference>
<Reference Include="log4net">
<HintPath>..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="zxing">
<HintPath>..\dll\zxing.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="CodeCreate.cs" />
<Compile Include="FrmBase.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmBase.Designer.cs">
<DependentUpon>FrmBase.cs</DependentUpon>
</Compile>
<Compile Include="FrmSplicingConfig.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmSplicingConfig.Designer.cs">
<DependentUpon>FrmSplicingConfig.cs</DependentUpon>
</Compile>
<Compile Include="FrmCodeEdit.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeEdit.Designer.cs">
<DependentUpon>FrmCodeEdit.cs</DependentUpon>
</Compile>
<Compile Include="FrmCodeSplicing.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmCodeSplicing.Designer.cs">
<DependentUpon>FrmCodeSplicing.cs</DependentUpon>
</Compile>
<Compile Include="FrmMain.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmMain.Designer.cs">
<DependentUpon>FrmMain.cs</DependentUpon>
</Compile>
<Compile Include="FrmMenu.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmMenu.Designer.cs">
<DependentUpon>FrmMenu.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="FrmBase.resx">
<DependentUpon>FrmBase.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmSplicingConfig.resx">
<DependentUpon>FrmSplicingConfig.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmCodeEdit.resx">
<DependentUpon>FrmCodeEdit.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmCodeSplicing.resx">
<DependentUpon>FrmCodeSplicing.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmMenu.resx">
<DependentUpon>FrmMenu.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{43cdd09e-fcf3-4960-a01d-3bbfe9933122}</Project>
<Name>Common</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="image\按钮切图_03.gif" />
</ItemGroup>
<ItemGroup>
<None Include="image\按钮切图_06.gif" />
</ItemGroup>
<ItemGroup>
<None Include="image\按钮切图_08.gif" />
</ItemGroup>
<ItemGroup>
<None Include="image\按钮切图_10.gif" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file \ No newline at end of file
namespace CodeSplicing
{
partial class FrmBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmBase));
this.SuspendLayout();
//
// FrmBase
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(331, 257);
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FrmBase";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "FrmBase";
this.ResumeLayout(false);
}
#endregion
}
}
\ No newline at end of file \ No newline at end of file
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;
namespace CodeSplicing
{
public partial class FrmBase : Form
{
public FrmBase()
{
InitializeComponent();
}
}
}

using CodeLibrary;
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
namespace CodeSplicing
{
public partial class FrmCodeEdit : Form
{
private List<CodeInfo> CodeResult = new List<CodeInfo>();
private String SplicingStr = "";
private HObject Ho_Image = null;
private PylonCamera camera = new PylonCamera();
private Stopwatch stopwatch = new Stopwatch();
public FrmCodeEdit()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void FrmMain_Load(object sender, EventArgs e)
{
string[] camerName = camera.GetName();
cmbCamera.Items.Clear();
foreach (string str in camerName)
{
cmbCamera.Items.Add(str);
}
if (camerName.Length > 0)
{
cmbCamera.SelectedIndex = 0;
}
HDLogUtil.logBox = this.richTextBox1;
}
private void btnSelImage_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Title = "选择二维码图片";
openDialog.Filter = "图片(*.jpg)|*.jpg|图片(*.png)|*.png";
//openDialog.DefaultExt = "png";
System.Windows.Forms.DialogResult result = openDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
txtPath.Text = openDialog.FileName;
string filename = txtPath.Text;
if (string.IsNullOrEmpty(filename))
{
MessageBox.Show("获取二维码图片为空");
}
pictureBox1.Image = null;
//读取图片内容
Image img = (Image)Image.FromFile(filename).Clone();
pictureBox1.Image = img;
Ho_Image = HDCodeHelper.Bitmap2HObjectBpp24(new Bitmap(img));
ShowImage(Ho_Image);
}
private void ShowCode(List<CodeInfo> list)
{
cmbCodeType1.SelectedIndex = 0;
cmbCodeType2.SelectedIndex = 0;
cmbCodeType3.SelectedIndex = 0;
cmbCodeType4.SelectedIndex = 0;
cmbCodeType5.SelectedIndex = 0;
lblCode1.Text = "";
lblCode2.Text = "";
lblCode3.Text = "";
lblCode4.Text = "";
lblCode5.Text = "";
list = (from m in list orderby m.Y descending select m).ToList<CodeInfo>();
SplicingStr = "RealID:";
if (list.Count > 0)
{
HDLogUtil.info("耗时:" + stopwatch.Elapsed.ToString()+"识别到二维码:");
int i = 0;
foreach (CodeInfo code in list)
{
HDLogUtil.info(" (X:" + code.X + ",Y:" + code.Y + ",角度:"+code.Orientation+") " + code.CodeStr);
if (i.Equals(0))
{
lblCode1.Text = code.CodeStr;
}
else if (i.Equals(1))
{
lblCode2.Text = code.CodeStr;
}
else if (i.Equals(2))
{
lblCode3.Text = code.CodeStr;
}
else if (i.Equals(3))
{
lblCode4.Text = code.CodeStr;
}
else if (i.Equals(4))
{
lblCode5.Text = code.CodeStr;
}
else if (i.Equals(5))
{
}
i++;
}
}
else
{
HDLogUtil.info("未识别到二维码");
SplicingStr = "";
}
if (SplicingStr.EndsWith("*"))
{
SplicingStr = SplicingStr.Substring(0, SplicingStr.Length - 1);
}
}
private void button7_Click(object sender, EventArgs e)
{
HDLogUtil.ClearLog();
}
private void button8_Click(object sender, EventArgs e)
{
int index = cmbCamera.SelectedIndex;
if (index < 0)
{
MessageBox.Show("请先选择相机");
return;
}
camera.Open(index);
Bitmap bit = camera.syncShot();
if (bit != null)
{
pictureBox1.Image = bit;
}
camera.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnHalconP_Click(object sender, EventArgs e)
{
if (Ho_Image == null)
{
MessageBox.Show("请先选择图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
HDLogUtil.ClearLog();
stopwatch.Restart();
HDCodeHelper.HalconWindow = this.hWindowControl1.HalconWindow;
CodeResult = HDCodeHelper.DecodeBarCode(Ho_Image);
ShowCode(CodeResult);
}
public void ShowImage(HObject ho_Image)
{
HTuple width, height;
HOperatorSet.GetImageSize(ho_Image, out width, out height);
int dWidth = (int)width.D;
int dHeight = (int)height.D;
this.hWindowControl1.HalconWindow.SetPart(0, 0, dHeight, dWidth);
HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);
}
private Stopwatch createStopWarch = new Stopwatch();
private bool isInProcess = false;
private void btnSplicing_Click(object sender, EventArgs e)
{
string filePath = Application.StartupPath + @"\codeImage\";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
if (lblCode1.Text.Equals(""))
{
MessageBox.Show("请先解析条码!", "提示");
return;
}
}
public string ReplaceName(string filename)
{
string str = filename;
str = str.Replace("\\", string.Empty);
str = str.Replace("/", string.Empty);
str = str.Replace(":", string.Empty);
str = str.Replace("*", string.Empty);
str = str.Replace("?", string.Empty);
str = str.Replace("\"", string.Empty);
str = str.Replace("<", string.Empty);
str = str.Replace(">", string.Empty);
str = str.Replace("|", string.Empty);
str = str.Replace(" ", string.Empty); //前面的替换会产生空格,最后将其一并替换掉
return str;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeSplicing
{
public partial class FrmCodeText : Form
{
public FrmCodeText()
{
InitializeComponent();
CboField.Items.AddRange(Asa.Common.Config.Field.ToArray());
}
public int Start { get; private set; }
public int Len { get; private set; }
public string Texts { get; private set; }
public string Field { get; private set; }
public FrmCodeText(string s, string field, int start, int len) : this()
{
Texts = s;
CboField.Text = field;
Start = start;
Len = len;
NudStart.Value = start;
NudLen.Value = len;
}
private void ShowText()
{
if (Start > 0)
lblText1.Text = Texts.Substring(0, Start);
else
lblText1.Text = "";
lblText2.Text = Texts.Substring(Start, Len);
if (Start + Len < Texts.Length)
lblText3.Text = Texts.Substring(Start + Len, Texts.Length - Start - Len);
else
lblText3.Text = "";
}
private void NudStart_ValueChanged(object sender, EventArgs e)
{
int n = Convert.ToInt32(NudStart.Value);
if (n + Len > Texts.Length)
{
NudStart.Value--;
}
else
{
Start = n;
ShowText();
}
}
private void NudLen_ValueChanged(object sender, EventArgs e)
{
int n = Convert.ToInt32(NudLen.Value);
if (Start + n > Texts.Length)
{
NudLen.Value--;
}
else
{
Len = n;
ShowText();
}
}
private void BtnAll_Click(object sender, EventArgs e)
{
//start = 0;
//len = text.Length;
NudStart.Value = 0;
NudLen.Value = Texts.Length;
}
private void BtnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void CboField_SelectedIndexChanged(object sender, EventArgs e)
{
Field = CboField.Text;
}
private void FrmCodeText_Load(object sender, EventArgs e)
{
Asa.Common.Language.SetLanguage(this);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file \ No newline at end of file
namespace CodeSplicing
{
partial class FrmMain
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeSplicing
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
}
}
using System.Drawing;
namespace CodeSplicing
{
partial class FrmMenu
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMenu));
this.btnProgram = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.btnProduct = new System.Windows.Forms.Button();
this.btnWelding = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnProgram
//
this.btnProgram.BackColor = System.Drawing.Color.Transparent;
this.btnProgram.BackgroundImage = global::CodeSplicing.Properties.Resources.按钮切图_08;
this.btnProgram.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btnProgram.FlatAppearance.BorderSize = 0;
this.btnProgram.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnProgram.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnProgram.ForeColor = System.Drawing.Color.White;
this.btnProgram.Location = new System.Drawing.Point(79, 212);
this.btnProgram.Name = "btnProgram";
this.btnProgram.Size = new System.Drawing.Size(250, 113);
this.btnProgram.TabIndex = 7;
this.btnProgram.UseVisualStyleBackColor = false;
this.btnProgram.Click += new System.EventHandler(this.btnProgram_Click);
//
// btnExit
//
this.btnExit.BackColor = System.Drawing.Color.Transparent;
this.btnExit.BackgroundImage = global::CodeSplicing.Properties.Resources.按钮切图_10;
this.btnExit.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btnExit.FlatAppearance.BorderSize = 0;
this.btnExit.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnExit.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnExit.ForeColor = System.Drawing.Color.White;
this.btnExit.Location = new System.Drawing.Point(335, 212);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(250, 113);
this.btnExit.TabIndex = 6;
this.btnExit.UseVisualStyleBackColor = false;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// btnProduct
//
this.btnProduct.BackColor = System.Drawing.Color.Transparent;
this.btnProduct.BackgroundImage = global::CodeSplicing.Properties.Resources.按钮切图_06;
this.btnProduct.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btnProduct.FlatAppearance.BorderSize = 0;
this.btnProduct.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnProduct.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnProduct.ForeColor = System.Drawing.Color.White;
this.btnProduct.Location = new System.Drawing.Point(335, 93);
this.btnProduct.Name = "btnProduct";
this.btnProduct.Size = new System.Drawing.Size(250, 113);
this.btnProduct.TabIndex = 1;
this.btnProduct.UseVisualStyleBackColor = false;
this.btnProduct.Click += new System.EventHandler(this.btnProduct_Click);
//
// btnWelding
//
this.btnWelding.BackColor = System.Drawing.Color.Transparent;
this.btnWelding.BackgroundImage = global::CodeSplicing.Properties.Resources.按钮切图_03;
this.btnWelding.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btnWelding.FlatAppearance.BorderSize = 0;
this.btnWelding.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnWelding.Font = new System.Drawing.Font("微软雅黑", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnWelding.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
this.btnWelding.Location = new System.Drawing.Point(79, 93);
this.btnWelding.Name = "btnWelding";
this.btnWelding.Size = new System.Drawing.Size(250, 113);
this.btnWelding.TabIndex = 0;
this.btnWelding.UseVisualStyleBackColor = false;
this.btnWelding.Click += new System.EventHandler(this.btnWelding_Click);
//
// FrmMenu
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(672, 408);
this.Controls.Add(this.btnProgram);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnProduct);
this.Controls.Add(this.btnWelding);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FrmMenu";
this.Text = "条形码拼接";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmMenu_FormClosing);
this.Load += new System.EventHandler(this.FrmMenu_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnWelding;
private System.Windows.Forms.Button btnProduct;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.Button btnProgram;
}
}
\ No newline at end of file \ No newline at end of file
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.Diagnostics;
using System.IO;
namespace CodeSplicing
{
public partial class FrmMenu : FrmBase
{
/// <summary>
/// 是否已经按了按钮,没有按时才会自动进入机器人焊接界面
/// </summary>
private bool isClick = false;
public FrmMenu()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
this.MaximizeBox = false;
this.MinimizeBox = false;
}
private void FrmMenu_Load(object sender, EventArgs e)
{
}
private void btnWelding_Click(object sender, EventArgs e)
{
FrmCodeSplicing fw = new FrmCodeSplicing();
this.Visible = false; ;
fw.ShowDialog();
this.Visible = true;
}
private void btnProduct_Click(object sender, EventArgs e)
{
FrmSplicingConfig fw = new FrmSplicingConfig();
this.Visible = false; ;
fw.ShowDialog();
this.Visible = true;
}
private void FrmMenu_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnProgram_Click(object sender, EventArgs e)
{
FrmCodeEdit fw = new FrmCodeEdit();
this.Visible = false; ;
fw.ShowDialog();
this.Visible = true;
}
}
}
namespace CodeSplicing
{
partial class FrmResize
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.BtnOK = new System.Windows.Forms.Button();
this.NudX = new System.Windows.Forms.NumericUpDown();
this.NudH = new System.Windows.Forms.NumericUpDown();
this.label21 = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.NudW = new System.Windows.Forms.NumericUpDown();
this.NudY = new System.Windows.Forms.NumericUpDown();
this.label19 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.NudX)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NudH)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NudW)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NudY)).BeginInit();
this.SuspendLayout();
//
// BtnOK
//
this.BtnOK.Location = new System.Drawing.Point(145, 96);
this.BtnOK.Name = "BtnOK";
this.BtnOK.Size = new System.Drawing.Size(100, 30);
this.BtnOK.TabIndex = 43;
this.BtnOK.Text = "确定";
this.BtnOK.UseVisualStyleBackColor = true;
this.BtnOK.Click += new System.EventHandler(this.BtnOK_Click);
//
// NudX
//
this.NudX.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.NudX.Location = new System.Drawing.Point(43, 15);
this.NudX.Margin = new System.Windows.Forms.Padding(6);
this.NudX.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NudX.Name = "NudX";
this.NudX.Size = new System.Drawing.Size(75, 29);
this.NudX.TabIndex = 36;
//
// NudH
//
this.NudH.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.NudH.Location = new System.Drawing.Point(168, 56);
this.NudH.Margin = new System.Windows.Forms.Padding(6);
this.NudH.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NudH.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.NudH.Name = "NudH";
this.NudH.Size = new System.Drawing.Size(75, 29);
this.NudH.TabIndex = 42;
this.NudH.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// label21
//
this.label21.AutoSize = true;
this.label21.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label21.Location = new System.Drawing.Point(14, 18);
this.label21.Margin = new System.Windows.Forms.Padding(6);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(20, 21);
this.label21.TabIndex = 35;
this.label21.Text = "X";
//
// label18
//
this.label18.AutoSize = true;
this.label18.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label18.Location = new System.Drawing.Point(134, 60);
this.label18.Margin = new System.Windows.Forms.Padding(6);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(22, 21);
this.label18.TabIndex = 41;
this.label18.Text = "H";
//
// label20
//
this.label20.AutoSize = true;
this.label20.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label20.Location = new System.Drawing.Point(14, 60);
this.label20.Margin = new System.Windows.Forms.Padding(6);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(20, 21);
this.label20.TabIndex = 37;
this.label20.Text = "Y";
//
// NudW
//
this.NudW.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.NudW.Location = new System.Drawing.Point(168, 15);
this.NudW.Margin = new System.Windows.Forms.Padding(6);
this.NudW.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NudW.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.NudW.Name = "NudW";
this.NudW.Size = new System.Drawing.Size(75, 29);
this.NudW.TabIndex = 40;
this.NudW.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// NudY
//
this.NudY.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.NudY.Location = new System.Drawing.Point(43, 56);
this.NudY.Margin = new System.Windows.Forms.Padding(6);
this.NudY.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NudY.Name = "NudY";
this.NudY.Size = new System.Drawing.Size(75, 29);
this.NudY.TabIndex = 38;
//
// label19
//
this.label19.AutoSize = true;
this.label19.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label19.Location = new System.Drawing.Point(130, 19);
this.label19.Margin = new System.Windows.Forms.Padding(6);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(26, 21);
this.label19.TabIndex = 39;
this.label19.Text = "W";
//
// FrmResize
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Info;
this.ClientSize = new System.Drawing.Size(257, 138);
this.Controls.Add(this.BtnOK);
this.Controls.Add(this.NudX);
this.Controls.Add(this.NudH);
this.Controls.Add(this.label21);
this.Controls.Add(this.label18);
this.Controls.Add(this.label20);
this.Controls.Add(this.NudW);
this.Controls.Add(this.NudY);
this.Controls.Add(this.label19);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FrmResize";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = " ";
this.Load += new System.EventHandler(this.FrmResize_Load);
((System.ComponentModel.ISupportInitialize)(this.NudX)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NudH)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NudW)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NudY)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button BtnOK;
private System.Windows.Forms.NumericUpDown NudX;
private System.Windows.Forms.NumericUpDown NudH;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.NumericUpDown NudW;
private System.Windows.Forms.NumericUpDown NudY;
private System.Windows.Forms.Label label19;
}
}
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeSplicing
{
public partial class FrmResize : Form
{
public Rectangle Rect { private set; get; }
public FrmResize()
{
InitializeComponent();
}
public FrmResize(Size size) : this()
{
NudX.Enabled = false;
NudY.Enabled = false;
NudW.Value = size.Width;
NudH.Value = size.Height;
}
public FrmResize(Rectangle rect) : this()
{
NudX.Value = rect.X < 0 ? 0 : rect.X;
NudY.Value = rect.Y < 0 ? 0 : rect.Y;
NudW.Value = rect.Width <= 0 ? 1 : rect.Width;
NudH.Value = rect.Height <= 0 ? 1 : rect.Height;
}
private void BtnOK_Click(object sender, EventArgs e)
{
Rect = new Rectangle(Convert.ToInt32(NudX.Value), Convert.ToInt32(NudY.Value), Convert.ToInt32(NudW.Value), Convert.ToInt32(NudH.Value));
DialogResult = DialogResult.OK;
}
private void FrmResize_Load(object sender, EventArgs e)
{
Asa.Common.Language.SetLanguage(this);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file \ No newline at end of file
using HalconDotNet;
namespace CodeSplicing
{
partial class FrmSplicingConfig
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmSplicingConfig));
this.btnSave = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.txtConfig = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.lblText = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// btnSave
//
this.btnSave.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnSave.Location = new System.Drawing.Point(466, 156);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(117, 33);
this.btnSave.TabIndex = 9;
this.btnSave.Tag = " ";
this.btnSave.Text = "保存";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnHalconP_Click);
//
// button7
//
this.button7.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.button7.Location = new System.Drawing.Point(466, 110);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(117, 33);
this.button7.TabIndex = 12;
this.button7.Text = "清理日志";
this.button7.UseVisualStyleBackColor = true;
//
// btnExit
//
this.btnExit.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnExit.Location = new System.Drawing.Point(466, 202);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(117, 33);
this.btnExit.TabIndex = 18;
this.btnExit.Text = "退出";
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.lblText);
this.panel1.Controls.Add(this.txtConfig);
this.panel1.Controls.Add(this.label10);
this.panel1.Controls.Add(this.btnExit);
this.panel1.Controls.Add(this.button7);
this.panel1.Controls.Add(this.btnSave);
this.panel1.Location = new System.Drawing.Point(11, 12);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(674, 304);
this.panel1.TabIndex = 28;
//
// txtConfig
//
this.txtConfig.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.txtConfig.Location = new System.Drawing.Point(123, 57);
this.txtConfig.Name = "txtConfig";
this.txtConfig.Size = new System.Drawing.Size(487, 26);
this.txtConfig.TabIndex = 38;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.label10.Location = new System.Drawing.Point(49, 60);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(68, 20);
this.label10.TabIndex = 37;
this.label10.Text = "拼接格式:";
//
// lblText
//
this.lblText.Font = new System.Drawing.Font("幼圆", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.lblText.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.lblText.Location = new System.Drawing.Point(146, 110);
this.lblText.Name = "lblText";
this.lblText.Size = new System.Drawing.Size(283, 145);
this.lblText.TabIndex = 39;
this.lblText.Text = "二维码内容";
//
// FrmSplicingConfig
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Info;
this.ClientSize = new System.Drawing.Size(706, 328);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FrmSplicingConfig";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "二维码拼接";
this.Load += new System.EventHandler(this.FrmMain_Load);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TextBox txtConfig;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label lblText;
}
}

using CodeLibrary;
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using Common;
namespace CodeSplicing
{
public partial class FrmSplicingConfig : Form
{
private List<CodeInfo> CodeResult = new List<CodeInfo>();
private String SplicingStr = "";
private HObject Ho_Image = null;
private Stopwatch stopwatch = new Stopwatch();
public FrmSplicingConfig()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void FrmMain_Load(object sender, EventArgs e)
{
//RID* PN*MPN * QTY * DATE * LOT
lblText.Text = "拼接格式说明:*为分隔符 " + "\r\nRID表示RealID对应的条码内容"
+ "\r\nPN表示Customer PN 对应的条码内容"
+ "\r\nQTY表示QTY对应的条码内容"
+ "\r\nDATE表示DATE对应的条码内容"
+ "\r\nLOT表示LOT对应的条码内容";
string config = ConfigAppSettings.GetValue(Setting_Init.SplicingStrConfig);
txtConfig.Text = config;
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnHalconP_Click(object sender, EventArgs e)
{
string str = txtConfig.Text;
//TODO 验证是否符合规则
ConfigAppSettings.SaveValue(Setting_Init.SplicingStrConfig, str);
MessageBox.Show("保存成功");
}
private Stopwatch createStopWarch = new Stopwatch();
private bool isInProcess = false;
private void btnSplicing_Click(object sender, EventArgs e)
{
string currStr = SplicingStr;
string filePath = Application.StartupPath + @"\codeImage\";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
if (currStr.Equals(""))
{
MessageBox.Show("请先解析条码!", "提示");
return;
}
if (isInProcess)
{
MessageBox.Show("请等待上个二维码生成成功后再操作!", "提示");
return;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="CmsCamera.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>9, 9</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>47</value>
</metadata>
</root>
\ No newline at end of file \ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeSplicing
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMenu());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CodeSplicing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CodeSplicing")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7c2222b4-e0d9-41fe-a5ff-09592344ce85")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace CodeSplicing.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CodeSplicing.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 使用此强类型资源类,为所有资源查找
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap 按钮切图_03 {
get {
object obj = ResourceManager.GetObject("按钮切图_03", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap 按钮切图_06 {
get {
object obj = ResourceManager.GetObject("按钮切图_06", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap 按钮切图_08 {
get {
object obj = ResourceManager.GetObject("按钮切图_08", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap 按钮切图_10 {
get {
object obj = ResourceManager.GetObject("按钮切图_10", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="按钮切图_08" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\image\按钮切图_08.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="按钮切图_06" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\image\按钮切图_06.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="按钮切图_03" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\image\按钮切图_03.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="按钮切图_10" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\image\按钮切图_10.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>
\ No newline at end of file \ No newline at end of file
此文件类型无法预览
此文件类型无法预览
此文件太大,无法显示。
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!