ModBase.vb 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578
  1. Imports System.IO.Compression
  2. Imports System.Management
  3. Imports System.Security.Cryptography
  4. Imports System.Security.Principal
  5. Imports System.Windows.Markup
  6. Imports Newtonsoft.Json
  7. Public Module ModBase
  8. #Region "声明"
  9. '下列版本信息由更新器自动修改
  10. Public Const VersionBaseName As String = "2.4.5" '不含分支前缀的显示用版本名
  11. Public Const VersionStandardCode As String = "2.4.5." & VersionBranchCode '标准格式的四段式版本号
  12. #If BETA Then
  13. Public Const VersionCode As Integer = 274 'Release
  14. #Else
  15. Public Const VersionCode As Integer = 275 'Snapshot
  16. #End If
  17. '自动生成的版本信息
  18. Public Const VersionDisplayName As String = VersionBranchName & " " & VersionBaseName
  19. #If RELEASE Then
  20. Public Const VersionBranchName As String = "Snapshot"
  21. Public Const VersionBranchCode As String = "0"
  22. #ElseIf BETA Then
  23. Public Const VersionBranchName As String = "Release"
  24. Public Const VersionBranchCode As String = "50"
  25. #ElseIf DEBUG Then
  26. Public Const VersionBranchName As String = "Debug"
  27. Public Const VersionBranchCode As String = "100"
  28. #End If
  29. ''' <summary>
  30. ''' 主窗口句柄。
  31. ''' </summary>
  32. Public Handle As IntPtr
  33. ''' <summary>
  34. ''' 程序的启动路径,以“\”结尾。
  35. ''' </summary>
  36. Public Path As String = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
  37. ''' <summary>
  38. ''' 包含程序名的完整路径。
  39. ''' </summary>
  40. Public PathWithName As String = Path & AppDomain.CurrentDomain.SetupInformation.ApplicationName
  41. ''' <summary>
  42. ''' 程序内嵌图片文件夹路径,以“/”结尾。
  43. ''' </summary>
  44. Public PathImage As String = "pack://application:,,,/images/"
  45. ''' <summary>
  46. ''' 当前程序的语言。
  47. ''' </summary>
  48. Public Lang As String = "zh_CN"
  49. ''' <summary>
  50. ''' 设置对象。
  51. ''' </summary>
  52. Public Setup As New ModSetup
  53. ''' <summary>
  54. ''' 程序的打开计时。
  55. ''' </summary>
  56. Public ApplicationStartTick As Long
  57. ''' <summary>
  58. ''' 程序打开时的时间。
  59. ''' </summary>
  60. Public ApplicationOpenTime As Date = Date.Now
  61. ''' <summary>
  62. ''' 设备唯一标识符。
  63. ''' </summary>
  64. Public UniqueAddress As String = SecretGetUniqueAddress()
  65. ''' <summary>
  66. ''' 程序是否已结束。
  67. ''' </summary>
  68. Public IsProgramEnded As Boolean = False
  69. ''' <summary>
  70. ''' 是否为 32 位系统。
  71. ''' </summary>
  72. Public Is32BitSystem As Boolean = Not Environment.Is64BitOperatingSystem
  73. ''' <summary>
  74. ''' 操作系统版本。Win10 为 10.0。
  75. ''' </summary>
  76. Public OsVersion As Version = Environment.OSVersion.Version
  77. ''' <summary>
  78. ''' 系统盘盘符,以 \ 结尾。例如 “C:\”。
  79. ''' </summary>
  80. Public OsDrive As String = Environment.GetLogicalDrives().First.ToUpper.First & ":\"
  81. ''' <summary>
  82. ''' 程序的缓存文件夹路径,以 \ 结尾。
  83. ''' </summary>
  84. Public PathTemp As String = If(Setup.Get("SystemSystemCache") = "", IO.Path.GetTempPath() & "PCL\", Setup.Get("SystemSystemCache")).ToString.Replace("/", "\").TrimEnd("\") & "\"
  85. ''' <summary>
  86. ''' AppData 中的 PCL 文件夹路径,以 \ 结尾。
  87. ''' </summary>
  88. Public PathAppdata As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\PCL\"
  89. #End Region
  90. #Region "矢量图标"
  91. Public Class Logo
  92. ''' <summary>
  93. ''' 图标按钮,心(空心),1.1x
  94. ''' </summary>
  95. Public Const IconButtonLikeLine As String = "M512 896a42.666667 42.666667 0 0 1-30.293333-12.373333l-331.52-331.946667a224.426667 224.426667 0 0 1 0-315.733333 223.573333 223.573333 0 0 1 315.733333 0L512 282.026667l46.08-46.08a223.573333 223.573333 0 0 1 315.733333 0 224.426667 224.426667 0 0 1 0 315.733333l-331.52 331.946667A42.666667 42.666667 0 0 1 512 896zM308.053333 256a136.533333 136.533333 0 0 0-97.28 40.106667 138.24 138.24 0 0 0 0 194.986666L512 792.746667l301.226667-301.653334a138.24 138.24 0 0 0 0-194.986666 141.653333 141.653333 0 0 0-194.56 0l-76.373334 76.8a42.666667 42.666667 0 0 1-60.586666 0L405.333333 296.106667A136.533333 136.533333 0 0 0 308.053333 256z"
  96. ''' <summary>
  97. ''' 图标按钮,心(实心),1.1x
  98. ''' </summary>
  99. Public Const IconButtonLikeFill As String = "M700.856 155.543c-74.769 0-144.295 72.696-190.046 127.26-45.737-54.576-115.247-127.26-190.056-127.26-134.79 0-244.443 105.78-244.443 235.799 0 77.57 39.278 131.988 70.845 175.713C238.908 694.053 469.62 852.094 479.39 858.757c9.41 6.414 20.424 9.629 31.401 9.629 11.006 0 21.998-3.215 31.398-9.63 9.782-6.662 240.514-164.703 332.238-291.701 31.587-43.724 70.874-98.143 70.874-175.713-0.001-130.02-109.656-235.8-244.445-235.8z m0 0"
  100. ''' <summary>
  101. ''' 图标按钮,垃圾桶,1.1x
  102. ''' </summary>
  103. Public Const IconButtonDelete As String = "M520.192 0C408.43 0 317.44 82.87 313.563 186.734H52.736c-29.038 0-52.663 21.943-52.663 49.079s23.625 49.152 52.663 49.152h58.075v550.473c0 103.35 75.118 187.757 167.717 187.757h472.43c92.599 0 167.716-83.894 167.716-187.757V285.477h52.59c29.038 0 52.59-21.943 52.663-49.08-0.073-27.135-23.625-49.151-52.663-49.151H726.235C723.237 83.017 631.955 0 520.192 0zM404.846 177.957c3.803-50.03 50.176-89.015 107.447-89.015 57.197 0 103.57 38.985 106.788 89.015H404.92zM284.379 933.669c-33.353 0-69.997-39.351-69.997-95.525v-549.01H833.39v549.522c0 56.247-36.645 95.525-69.998 95.525H284.379v-0.512z M357.23 800.695a48.274 48.274 0 0 0 47.616-49.006V471.7a48.274 48.274 0 0 0-47.543-49.08 48.274 48.274 0 0 0-47.69 49.006V751.69c0 27.282 20.846 49.006 47.617 49.006z m166.62 0a48.274 48.274 0 0 0 47.688-49.006V471.7a48.274 48.274 0 0 0-47.689-49.08 48.274 48.274 0 0 0-47.543 49.006V751.69c0 27.282 21.431 49.006 47.543 49.006z m142.92 0a48.274 48.274 0 0 0 47.543-49.006V471.7a48.274 48.274 0 0 0-47.543-49.08 48.274 48.274 0 0 0-47.616 49.006V751.69c0 27.282 20.773 49.006 47.543 49.006z"
  104. ''' <summary>
  105. ''' 图标按钮,笔,1x
  106. ''' </summary>
  107. Public Const IconButtonEdit As String = "M732.64 64.32C688.576 21.216 613.696 21.216 569.6 64.32L120.128 499.52c-17.6 12.896-26.432 30.144-30.848 51.68L32 870.048c0 25.856 8.8 56 26.432 73.248 17.632 17.216 17.632 48.704 88.64 48.704h13.248l326.08-56c22.016-4.32 39.68-12.928 52.864-30.176l449.472-435.2c22.048-21.536 35.264-47.36 35.264-77.536 0-30.176-13.216-56-35.264-77.568l-256.096-251.2zM139.712 903.776l56-326.912 311.04-295.136 267.104 269.44-310.976 295.168-323.168 57.44zM844.576 467.84l-273.984-260.672 61.856-59.84c8.832-8.512 26.528-8.512 39.776 0l234.24 226.496c4.384 4.288 8.832 12.8 8.832 17.088s-4.416 8.544-8.864 12.8l-61.856 64.128z"
  108. ''' <summary>
  109. ''' 图标按钮,齿轮,1.1x
  110. ''' </summary>
  111. Public Const IconButtonSetup As String = "M651.946667 1001.813333c-22.186667 0-42.666667-10.24-61.44-27.306666-23.893333-23.893333-49.493333-35.84-75.093334-35.84-29.013333 0-56.32 11.946667-73.386666 30.72v3.413333c-17.066667 17.066667-42.666667 27.306667-66.56 27.306667h-6.826667c-6.826667 0-11.946667-1.706667-15.36-1.706667l-6.826667-1.706667c-64.853333-20.48-121.173333-54.613333-168.96-98.986666-29.013333-23.893333-37.546667-63.146667-25.6-95.573334 8.533333-23.893333 5.12-51.2-10.24-75.093333-15.36-27.306667-34.133333-40.96-59.733333-47.786667h-1.706667l-5.12-1.706666c-35.84-8.533333-61.44-34.133333-66.56-69.973334C1.706667 575.146667 0 537.6 0 512c0-32.426667 3.413333-63.146667 8.533333-93.866667v-6.826666l3.413334-8.533334c10.24-23.893333 23.893333-40.96 44.373333-51.2 5.12-3.413333 11.946667-6.826667 20.48-8.533333 27.306667-8.533333 51.2-25.6 63.146667-44.373333 13.653333-23.893333 17.066667-52.906667 10.24-81.92-11.946667-34.133333 0-71.68 30.72-93.866667 44.373333-37.546667 97.28-68.266667 158.72-93.866667l3.413333-1.706666c44.373333-13.653333 75.093333 3.413333 92.16 20.48 23.893333 23.893333 49.493333 35.84 75.093333 35.84 30.72 0 56.32-10.24 71.68-30.72l3.413334-3.413334c27.306667-27.306667 63.146667-35.84 93.866666-22.186666 63.146667 22.186667 117.76 54.613333 165.546667 97.28 29.013333 23.893333 37.546667 63.146667 25.6 95.573333-8.533333 23.893333-5.12 51.2 10.24 75.093333 15.36 27.306667 34.133333 40.96 59.733333 47.786667h1.706667l5.12 1.706667c35.84 8.533333 61.44 34.133333 66.56 71.68 6.826667 30.72 10.24 63.146667 11.946667 93.866666v3.413334c0 32.426667-3.413333 63.146667-8.533334 93.866666v6.826667l-3.413333 8.533333c-10.24 23.893333-23.893333 40.96-44.373333 51.2-5.12 3.413333-11.946667 6.826667-20.48 8.533334-27.306667 8.533333-51.2 25.6-63.146667 46.08-13.653333 23.893333-17.066667 52.906667-10.24 81.92 11.946667 35.84-1.706667 75.093333-30.72 95.573333-44.373333 35.84-95.573333 66.56-157.013333 92.16-15.36 3.413333-27.306667 3.413333-35.84 3.413333z m3.413333-83.626666z m1.706667 0zM517.12 853.333333c47.786667 0 93.866667 20.48 134.826667 59.733334 1.706667 1.706667 3.413333 1.706667 3.413333 3.413333 52.906667-22.186667 97.28-49.493333 136.533333-80.213333l1.706667-1.706667v-3.413333c-13.653333-52.906667-8.533333-104.106667 17.066667-148.48 23.893333-39.253333 64.853333-69.973333 114.346666-85.333334 1.706667 0 3.413333-1.706667 6.826667-6.826666 5.12-25.6 8.533333-51.2 8.533333-78.506667-1.706667-29.013333-3.413333-56.32-10.24-81.92v-5.12h-1.706666c-51.2-11.946667-90.453333-39.253333-119.466667-87.04-27.306667-44.373333-34.133333-100.693333-17.066667-148.48l-1.706666-1.706667h-3.413334c-39.253333-35.84-85.333333-63.146667-136.533333-80.213333H648.533333s-1.706667 1.706667-3.413333 1.706667c-32.426667 39.253333-80.213333 59.733333-136.533333 59.733333-47.786667 0-93.866667-20.48-134.826667-59.733333l-1.706667-1.706667h-1.706666c-54.613333 22.186667-98.986667 49.493333-136.533334 80.213333l-1.706666 1.706667v3.413333c13.653333 52.906667 8.533333 104.106667-17.066667 148.48-23.893333 39.253333-64.853333 69.973333-114.346667 85.333334-1.706667 0-3.413333 1.706667-6.826666 6.826666-6.826667 25.6-8.533333 51.2-8.533334 78.506667 0 30.72 3.413333 58.026667 6.826667 76.8l1.706667 5.12h1.706666c51.2 11.946667 90.453333 39.253333 119.466667 87.04 27.306667 44.373333 34.133333 100.693333 17.066667 148.48l1.706666 1.706667 1.706667 1.706666c37.546667 35.84 83.626667 63.146667 134.826667 80.213334 1.706667 0 3.413333 0 3.413333 1.706666h1.706667s1.706667 0 5.12-1.706666c34.133333-37.546667 81.92-59.733333 136.533333-59.733334z m-6.826667-146.773333c-110.933333 0-199.68-85.333333-199.68-196.266667 0-109.226667 87.04-196.266667 199.68-196.266666s199.68 85.333333 199.68 196.266666c-1.706667 109.226667-88.746667 196.266667-199.68 196.266667z m0-307.2c-63.146667 0-114.346667 49.493333-114.346666 110.933333 0 63.146667 49.493333 110.933333 114.346666 110.933334 30.72 0 59.733333-11.946667 80.213334-32.426667 20.48-20.48 32.426667-49.493333 32.426666-78.506667 0-63.146667-49.493333-110.933333-112.64-110.933333z"
  112. ''' <summary>
  113. ''' 图标按钮,重置,0.9x
  114. ''' </summary>
  115. Public Const IconButtonReset As String = "M667.6817627 313.65283203l-45.28564454 55.76660156L858.06933594 391.27124023 787.61950684 165.93066406l-56.01379395 69.01611328A354.47387695 354.47387695 0 0 0 520.89892578 165.93066406C324.87536621 165.93066406 165.93066406 324.43041992 165.93066406 519.91015625c0 195.52917481 158.94470215 353.97949219 354.96826172 353.97949219a355.06713867 355.06713867 0 0 0 331.73217774-227.66418458 50.52612305 50.52612305 0 0 0-29.21813966-65.25878905 50.77331543 50.77331543 0 0 0-65.50598144 29.16870117A253.61938477 253.61938477 0 0 1 520.94836426 772.78796387c-140.05920411 0-253.61938477-113.21411133-253.61938477-252.87780762 0-139.61425781 113.56018067-252.82836914 253.61938477-252.82836914 53.59130859 0 104.46350098 16.61132813 146.73339843 46.57104492"
  116. ''' <summary>
  117. ''' 图标按钮,刷新,0.85x
  118. ''' </summary>
  119. Public Const IconButtonRefresh As String = "M875.52 148.48C783.36 56.32 655.36 0 512 0 291.84 0 107.52 138.24 30.72 332.8l122.88 46.08C204.8 230.4 348.16 128 512 128c107.52 0 199.68 40.96 271.36 112.64L640 384h384V0L875.52 148.48zM512 896c-107.52 0-199.68-40.96-271.36-112.64L384 640H0v384l148.48-148.48C240.64 967.68 368.64 1024 512 1024c220.16 0 404.48-138.24 481.28-332.8L870.4 645.12C819.2 793.6 675.84 896 512 896z"
  120. ''' <summary>
  121. ''' 图标按钮,软盘,1x
  122. ''' </summary>
  123. Public Const IconButtonSave As String = "M819.392 0L1024 202.752v652.16a168.96 168.96 0 0 1-168.832 168.768h-104.192a47.296 47.296 0 0 1-10.752 0H283.776a47.232 47.232 0 0 1-10.752 0H168.832A168.96 168.96 0 0 1 0 854.912V168.768A168.96 168.96 0 0 1 168.832 0h650.56z m110.208 854.912V242.112l-149.12-147.776H168.896c-41.088 0-74.432 33.408-74.432 74.432v686.144c0 41.024 33.344 74.432 74.432 74.432h62.4v-190.528c0-33.408 27.136-60.544 60.544-60.544h440.448c33.408 0 60.544 27.136 60.544 60.544v190.528h62.4c41.088 0 74.432-33.408 74.432-74.432z m-604.032 74.432h372.864v-156.736H325.568v156.736z m403.52-596.48a47.168 47.168 0 1 1 0 94.336H287.872a47.168 47.168 0 1 1 0-94.336h441.216z m0-153.728a47.168 47.168 0 1 1 0 94.4H287.872a47.168 47.168 0 1 1 0-94.4h441.216z"
  124. ''' <summary>
  125. ''' 图标按钮,信息,1.05x
  126. ''' </summary>
  127. Public Const IconButtonInfo As String = "M512 917.333333c223.861333 0 405.333333-181.472 405.333333-405.333333S735.861333 106.666667 512 106.666667 106.666667 288.138667 106.666667 512s181.472 405.333333 405.333333 405.333333z m0 106.666667C229.226667 1024 0 794.773333 0 512S229.226667 0 512 0s512 229.226667 512 512-229.226667 512-512 512z m-32-597.333333h64a21.333333 21.333333 0 0 1 21.333333 21.333333v320a21.333333 21.333333 0 0 1-21.333333 21.333333h-64a21.333333 21.333333 0 0 1-21.333333-21.333333V448a21.333333 21.333333 0 0 1 21.333333-21.333333z m0-192h64a21.333333 21.333333 0 0 1 21.333333 21.333333v64a21.333333 21.333333 0 0 1-21.333333 21.333333h-64a21.333333 21.333333 0 0 1-21.333333-21.333333v-64a21.333333 21.333333 0 0 1 21.333333-21.333333z"
  128. ''' <summary>
  129. ''' 图标按钮,列表,1x
  130. ''' </summary>
  131. Public Const IconButtonList As String = "M384 128h640v128H384zM160 192m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0ZM384 448h640v128H384zM160 512m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0ZM384 768h640v128H384zM160 832m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0Z"
  132. ''' <summary>
  133. ''' 图标按钮,文件夹,1.15x
  134. ''' </summary>
  135. Public Const IconButtonOpen As String = "M889.018182 418.909091H884.363636V316.509091a93.090909 93.090909 0 0 0-99.607272-89.832727h-302.545455l-93.090909-76.334546A46.545455 46.545455 0 0 0 358.865455 139.636364H146.152727A93.090909 93.090909 0 0 0 46.545455 229.469091V837.818182a46.545455 46.545455 0 0 0 46.545454 46.545454 46.545455 46.545455 0 0 0 16.756364-3.258181 109.381818 109.381818 0 0 0 25.134545 3.258181h586.472727a85.178182 85.178182 0 0 0 87.04-63.301818l163.374546-302.545454a46.545455 46.545455 0 0 0 5.585454-21.876364A82.385455 82.385455 0 0 0 889.018182 418.909091z m-744.727273-186.181818h198.283636l93.09091 76.334545a46.545455 46.545455 0 0 0 29.323636 10.705455h319.301818a12.101818 12.101818 0 0 1 6.516364 0V418.909091H302.545455a85.178182 85.178182 0 0 0-87.04 63.301818L139.636364 622.778182V232.727273a19.549091 19.549091 0 0 1 6.516363 0z m578.094546 552.029091a27.461818 27.461818 0 0 0-2.792728 6.516363H154.530909l147.083636-272.290909a27.461818 27.461818 0 0 0 2.792728-6.981818h565.061818z"
  136. ''' <summary>
  137. ''' 图标按钮,名片,1.1x
  138. ''' </summary>
  139. Public Const IconButtonCard As String = "M834.5 684.1c-31.2-70.4-98.9-120.9-179.1-127.3 63.5-8.5 112.6-63 112.6-128.8 0-71.8-58.2-130-130-130s-130 58.2-130 130c0 65.9 49 120.3 112.6 128.8-80.2 6.4-148 57-179.1 127.3-8.7 19.7 6 42 27.6 42 12.1 0 22.7-7.5 27.7-18.5 24.3-53.9 78.5-91.5 141.3-91.5s117 37.6 141.3 91.5c5 11.1 15.6 18.5 27.7 18.5 21.4 0 36.1-22.3 27.4-42zM567.9 427.9c0-38.6 31.4-70 70-70s70 31.4 70 70-31.4 70-70 70-70-31.4-70-70zM460.3 347.9H216.9c-16.6 0-30 13.4-30 30s13.4 30 30 30h243.3c16.6 0 30-13.4 30-30 0.1-16.5-13.4-30-29.9-30zM367.4 459.6H216.9c-16.6 0-30 13.4-30 30s13.4 30 30 30h150.4c16.6 0 30-13.4 30-30 0.1-16.6-13.4-30-29.9-30zM297.4 571.2H217c-16.6 0-30 13.4-30 30s13.4 30 30 30h80.4c16.6 0 30-13.4 30-30 0-16.5-13.5-30-30-30zM900 236v552H124V236h776m0-60H124c-33.1 0-60 26.9-60 60v552c0 33.1 26.9 60 60 60h776c33.1 0 60-26.9 60-60V236c0-33.1-26.9-60-60-60z"
  140. ''' <summary>
  141. ''' 图标按钮,×,0.85x
  142. ''' </summary>
  143. Public Const IconButtonCross As String = "F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z"
  144. ''' <summary>
  145. ''' 图标按钮,Mojang,1.1x
  146. ''' </summary>
  147. Public Const IconButtonMojang As String = "M9.183,18.967c-0.109-2.239,1.336-5.119,3.92-4.96c3.657-0.027,7.319-0.044,10.977,0.005 c3.712,0.214,6.596,2.759,9.652,4.533c0.181-1.697-0.197-3.717,1.237-4.982c1.899,2.091,3.143,4.894,5.677,6.334 c1.577,0.805,2.973-0.668,4.221-1.44c1.55,2.305,2.108,5.075,2.622,7.752c0.657,3.438,0.947,6.925,1.111,10.413 c-1.734-0.733-3.355-1.708-4.971-2.671c-1.396-4.933-5.349-8.656-9.723-11.059c-3.46-1.817-7.752-2.185-11.338-0.52 c-3.761,1.593-6.285,5.666-5.891,9.75c0.121,4.577,3.17,8.765,7.391,10.456c7.746,3.285,16.407,2.234,24.521,1.243 c0.454,2.315-1.511,4.527-3.695,4.889c-10.577,0.038-21.148-0.011-31.725,0.022c-2.217,0.279-4.079-1.879-3.964-4.008 C9.167,36.141,9.216,27.556,9.183,18.967z M40.114,8.09c0.294-0.801,0.872-1.417,1.542-1.924c1.379,2.589,2.742,5.482,2.311,8.491 c-0.332,2.54-4.42,2.507-5.052,0.163C38.349,12.527,39.209,10.178,40.114,8.09z M0,53 l0.1,0 z"
  148. ''' <summary>
  149. ''' 图标按钮,用户,0.95x
  150. ''' </summary>
  151. Public Const IconButtonUser As String = "M660.338 528.065c63.61-46.825 105.131-121.964 105.131-206.83 0-141.7-115.29-256.987-256.997-256.987-141.706 0-256.998 115.288-256.998 256.987 0 85.901 42.52 161.887 107.456 208.562-152.1 59.92-260.185 207.961-260.185 381.077 0 21.276 17.253 38.53 38.53 38.53 21.278 0 38.53-17.254 38.53-38.53 0-183.426 149.232-332.671 332.667-332.671 1.589 0 3.113-0.207 4.694-0.244 0.8 0.056 1.553 0.244 2.362 0.244 183.434 0 332.664 149.245 332.664 332.671 0 21.276 17.255 38.53 38.533 38.53 21.277 0 38.53-17.254 38.53-38.53 0-174.885-110.354-324.13-264.917-382.809z m-331.803-206.83c0-99.22 80.72-179.927 179.935-179.927s179.937 80.708 179.937 179.927c0 99.203-80.721 179.91-179.937 179.91s-179.935-80.708-179.935-179.91z"
  152. ''' <summary>
  153. ''' 图标,音符,1x
  154. ''' </summary>
  155. Public Const IconMusic As String = "M348.293565 716.53287V254.797913c0-41.672348 28.004174-78.358261 68.919652-90.37913L815.994435 40.826435c62.775652-18.610087 125.907478 26.579478 125.907478 89.933913v539.158261c8.013913 42.25113-8.94887 89.177043-47.014956 127.109565a232.848696 232.848696 0 0 1-170.785392 65.758609c-61.885217-2.938435-111.081739-33.435826-129.113043-80.050087-18.031304-46.614261-2.137043-102.177391 41.672348-145.853218a232.848696 232.848696 0 0 1 170.785391-65.80313c21.014261 1.024 40.514783 5.164522 57.878261 12.065391V233.338435c0-12.109913-10.551652-20.034783-20.569044-20.034783a24.620522 24.620522 0 0 0-5.787826 0.934957L439.785739 338.18713a19.545043 19.545043 0 0 0-14.825739 19.144348v438.984348H423.846957c11.53113 43.987478-5.164522 94.208-45.412174 134.322087a232.848696 232.848696 0 0 1-170.785392 65.758609c-61.885217-2.938435-111.081739-33.435826-129.113043-80.050087-18.031304-46.614261-2.137043-102.177391 41.672348-145.853218a232.848696 232.848696 0 0 1 170.785391-65.80313c20.791652 1.024 40.069565 5.075478 57.299478 11.842783z"
  156. ''' <summary>
  157. ''' 图标,播放,0.8x
  158. ''' </summary>
  159. Public Const IconPlay As String = "M803.904 463.936a55.168 55.168 0 0 1 0 96.128l-463.616 264.448C302.848 845.888 256 819.136 256 776.448V247.616c0-42.752 46.848-69.44 84.288-48.064l463.616 264.384z"
  160. End Class
  161. #End Region
  162. #Region "自定义类"
  163. ''' <summary>
  164. ''' 支持小数与常见类型隐式转换的颜色。
  165. ''' </summary>
  166. Public Class MyColor
  167. Public A As Double = 255
  168. Public R As Double = 0
  169. Public G As Double = 0
  170. Public B As Double = 0
  171. '类型转换
  172. Public Shared Widening Operator CType(str As String) As MyColor
  173. Return New MyColor(str)
  174. End Operator
  175. Public Shared Widening Operator CType(col As Color) As MyColor
  176. Return New MyColor(col)
  177. End Operator
  178. Public Shared Widening Operator CType(conv As MyColor) As Color
  179. Return Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  180. End Operator
  181. Public Shared Widening Operator CType(conv As MyColor) As System.Drawing.Color
  182. Return System.Drawing.Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  183. End Operator
  184. Public Shared Widening Operator CType(bru As SolidColorBrush) As MyColor
  185. Return New MyColor(bru.Color)
  186. End Operator
  187. Public Shared Widening Operator CType(conv As MyColor) As SolidColorBrush
  188. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  189. End Operator
  190. Public Shared Widening Operator CType(bru As Brush) As MyColor
  191. Return New MyColor(bru)
  192. End Operator
  193. Public Shared Widening Operator CType(conv As MyColor) As Brush
  194. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  195. End Operator
  196. '颜色运算
  197. Public Shared Operator +(a As MyColor, b As MyColor) As MyColor
  198. Return New MyColor With {.A = a.A + b.A, .B = a.B + b.B, .G = a.G + b.G, .R = a.R + b.R}
  199. End Operator
  200. Public Shared Operator -(a As MyColor, b As MyColor) As MyColor
  201. Return New MyColor With {.A = a.A - b.A, .B = a.B - b.B, .G = a.G - b.G, .R = a.R - b.R}
  202. End Operator
  203. Public Shared Operator *(a As MyColor, b As Double) As MyColor
  204. Return New MyColor With {.A = a.A * b, .B = a.B * b, .G = a.G * b, .R = a.R * b}
  205. End Operator
  206. Public Shared Operator /(a As MyColor, b As Double) As MyColor
  207. Return New MyColor With {.A = a.A / b, .B = a.B / b, .G = a.G / b, .R = a.R / b}
  208. End Operator
  209. Public Shared Operator =(a As MyColor, b As MyColor) As Boolean
  210. If IsNothing(a) AndAlso IsNothing(b) Then Return True
  211. If IsNothing(a) OrElse IsNothing(b) Then Return False
  212. Return a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B
  213. End Operator
  214. Public Shared Operator <>(a As MyColor, b As MyColor) As Boolean
  215. If IsNothing(a) AndAlso IsNothing(b) Then Return False
  216. If IsNothing(a) OrElse IsNothing(b) Then Return True
  217. Return Not (a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B)
  218. End Operator
  219. '构造函数
  220. Public Sub New()
  221. End Sub
  222. Public Sub New(col As Color)
  223. Me.A = col.A
  224. Me.R = col.R
  225. Me.G = col.G
  226. Me.B = col.B
  227. End Sub
  228. Public Sub New(HexString As String)
  229. Dim StringColor As Media.Color = ColorConverter.ConvertFromString(HexString)
  230. A = StringColor.A
  231. R = StringColor.R
  232. G = StringColor.G
  233. B = StringColor.B
  234. End Sub
  235. Public Sub New(newA As Double, col As MyColor)
  236. Me.A = newA
  237. Me.R = col.R
  238. Me.G = col.G
  239. Me.B = col.B
  240. End Sub
  241. Public Sub New(newR As Double, newG As Double, newB As Double)
  242. Me.A = 255
  243. Me.R = newR
  244. Me.G = newG
  245. Me.B = newB
  246. End Sub
  247. Public Sub New(newA As Double, newR As Double, newG As Double, newB As Double)
  248. Me.A = newA
  249. Me.R = newR
  250. Me.G = newG
  251. Me.B = newB
  252. End Sub
  253. Public Sub New(brush As Brush)
  254. Dim Color As Color = CType(brush, SolidColorBrush).Color
  255. A = Color.A
  256. R = Color.R
  257. G = Color.G
  258. B = Color.B
  259. End Sub
  260. Public Sub New(brush As SolidColorBrush)
  261. Dim Color As Color = brush.Color
  262. A = Color.A
  263. R = Color.R
  264. G = Color.G
  265. B = Color.B
  266. End Sub
  267. Public Sub New(obj As Object)
  268. If obj Is Nothing Then
  269. A = 255 : R = 255 : G = 255 : B = 255
  270. Else
  271. If TypeOf obj Is SolidColorBrush Then
  272. '避免反复获取 Color 对象造成性能下降
  273. Dim Color As Color = CType(obj, SolidColorBrush).Color
  274. A = Color.A
  275. R = Color.R
  276. G = Color.G
  277. B = Color.B
  278. Else
  279. A = obj.A
  280. R = obj.R
  281. G = obj.G
  282. B = obj.B
  283. End If
  284. End If
  285. End Sub
  286. 'HSL
  287. Public Function Hue(v1 As Double, v2 As Double, vH As Double) As Double
  288. If vH < 0 Then vH += 1
  289. If vH > 1 Then vH -= 1
  290. If vH < 0.16667 Then Return v1 + (v2 - v1) * 6 * vH
  291. If vH < 0.5 Then Return v2
  292. If vH < 0.66667 Then Return v1 + (v2 - v1) * (4 - vH * 6)
  293. Return v1
  294. End Function
  295. Public Function FromHSL(sH As Double, sS As Double, sL As Double) As MyColor
  296. If sS = 0 Then
  297. R = sL * 2.55
  298. G = R
  299. B = R
  300. Else
  301. Dim H = sH / 360
  302. Dim S = sS / 100
  303. Dim L = sL / 100
  304. S = If(L < 0.5, S * L + L, S * (1.0 - L) + L)
  305. L = 2 * L - S
  306. R = 255 * Hue(L, S, H + 1 / 3)
  307. G = 255 * Hue(L, S, H)
  308. B = 255 * Hue(L, S, H - 1 / 3)
  309. End If
  310. A = 255
  311. Return Me
  312. End Function
  313. Public Function FromHSL2(sH As Double, sS As Double, sL As Double) As MyColor
  314. If sS = 0 Then
  315. R = sL * 2.55 : G = R : B = R
  316. Else
  317. '初始化
  318. sH = (sH + 3600000) Mod 360
  319. Dim cent As Double() = {
  320. +0.1, -0.06, -0.3, '0, 30, 60
  321. -0.19, -0.15, -0.24, '90, 120, 150
  322. -0.32, -0.09, +0.18, '180, 210, 240
  323. +0.05, -0.12, -0.02, '270, 300, 330
  324. +0.1, -0.06} '最后两位与前两位一致,加是变亮,减是变暗
  325. '计算色调对应的亮度片区
  326. Dim center As Double = sH / 30.0
  327. Dim intCenter As Integer = Math.Floor(center) '亮度片区编号
  328. center = 50 - (
  329. (1 - center + intCenter) * cent(intCenter) + (center - intCenter) * cent(intCenter + 1)
  330. ) * sS
  331. 'center = 50 + (cent(intCenter) + (center - intCenter) * (cent(intCenter + 1) - cent(intCenter))) * sS
  332. sL = If(sL < center, sL / center, 1 + (sL - center) / (100 - center)) * 50
  333. FromHSL(sH, sS, sL)
  334. End If
  335. A = 255
  336. Return Me
  337. End Function
  338. Public Overrides Function ToString() As String
  339. Return "(" & A & "," & R & "," & G & "," & B & ")"
  340. End Function
  341. Public Overrides Function Equals(obj As Object) As Boolean
  342. Return Me = obj
  343. End Function
  344. End Class
  345. ''' <summary>
  346. ''' 支持负数与浮点数的矩形。
  347. ''' </summary>
  348. Public Class MyRect
  349. '属性
  350. Public Property Width As Double = 0
  351. Public Property Height As Double = 0
  352. Public Property Left As Double = 0
  353. Public Property Top As Double = 0
  354. '构造函数
  355. Public Sub New()
  356. End Sub
  357. Public Sub New(left As Double, top As Double, width As Double, height As Double)
  358. Me.Left = left
  359. Me.Top = top
  360. Me.Width = width
  361. Me.Height = height
  362. End Sub
  363. End Class
  364. ''' <summary>
  365. ''' 模块加载状态枚举。
  366. ''' </summary>
  367. Public Enum LoadState
  368. Waiting
  369. Loading
  370. Finished
  371. Failed
  372. Aborted
  373. End Enum
  374. ''' <summary>
  375. ''' 执行返回值。
  376. ''' </summary>
  377. Public Enum Result
  378. ''' <summary>
  379. ''' 执行成功,或进程被中断。
  380. ''' </summary>
  381. Aborted = -1
  382. ''' <summary>
  383. ''' 执行成功。
  384. ''' </summary>
  385. Success = 0
  386. ''' <summary>
  387. ''' 执行失败。
  388. ''' </summary>
  389. Fail
  390. ''' <summary>
  391. ''' 执行时出现未经处理的异常。
  392. ''' </summary>
  393. Exception
  394. ''' <summary>
  395. ''' 执行超时。
  396. ''' </summary>
  397. Timeout
  398. ''' <summary>
  399. ''' 取消执行。可能是由于不满足执行的前置条件。
  400. ''' </summary>
  401. Cancel
  402. End Enum
  403. ''' <summary>
  404. ''' 可以使用 Equals 和等号的 List。
  405. ''' </summary>
  406. Public Class EqualableList(Of T)
  407. Inherits List(Of T)
  408. Public Overrides Function Equals(obj As Object) As Boolean
  409. If TryCast(obj, List(Of T)) Is Nothing Then
  410. '类型不同
  411. Return False
  412. Else
  413. '类型相同
  414. Dim objList As List(Of T) = obj
  415. If objList.Count <> Count Then Return False
  416. For i = 0 To objList.Count - 1
  417. If Not objList(i).Equals(Me(i)) Then Return False
  418. Next
  419. Return True
  420. End If
  421. End Function
  422. Public Shared Operator =(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  423. Return EqualityComparer(Of EqualableList(Of T)).Default.Equals(left, right)
  424. End Operator
  425. Public Shared Operator <>(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  426. Return Not left = right
  427. End Operator
  428. End Class
  429. #End Region
  430. #Region "数学"
  431. ''' <summary>
  432. ''' 2~65 进制的转换。
  433. ''' </summary>
  434. Public Function RadixConvert(Input As String, FromRadix As Integer, ToRadix As Integer) As String
  435. Const Digits As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+="
  436. '零与负数的处理
  437. If String.IsNullOrEmpty(Input) Then Return "0"
  438. Dim IsNegative As Boolean = Input.StartsWith("-")
  439. If IsNegative Then Input = Input.TrimStart("-")
  440. '转换为十进制
  441. Dim RealNum As Long = 0, Scale As Long = 1
  442. For Each Digit In Input.Reverse.Select(Function(l) Digits.IndexOf(l))
  443. RealNum += Digit * Scale
  444. Scale *= FromRadix
  445. Next
  446. '转换为指定进制
  447. Dim Result = ""
  448. While RealNum > 0
  449. Dim NewNum As Integer = RealNum Mod ToRadix
  450. RealNum = (RealNum - NewNum) / ToRadix
  451. Result = Digits(NewNum) & Result
  452. End While
  453. '负数的结束处理与返回
  454. Return If(IsNegative, "-", "") & Result
  455. End Function
  456. ''' <summary>
  457. ''' 计算二阶贝塞尔曲线。
  458. ''' </summary>
  459. Public Function MathBezier(x As Double, x1 As Double, y1 As Double, x2 As Double, y2 As Double, Optional acc As Double = 0.01) As Double
  460. If x <= 0 OrElse Double.IsNaN(x) Then Return 0
  461. If x >= 1 Then Return 1
  462. Dim a, b
  463. a = x
  464. Do
  465. b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1)
  466. a += (x - b) * 0.5
  467. Loop Until Math.Abs(b - x) < acc '精度
  468. Return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1)
  469. End Function
  470. ''' <summary>
  471. ''' 将一个数字限制为 0~255 的 Byte 值。
  472. ''' </summary>
  473. Public Function MathByte(d As Double) As Byte
  474. If d < 0 Then d = 0
  475. If d > 255 Then d = 255
  476. Return Math.Round(d)
  477. End Function
  478. ''' <summary>
  479. ''' 提供 MyColor 类型支持的 Math.Round。
  480. ''' </summary>
  481. Public Function MathRound(col As MyColor, Optional w As Integer = 0) As MyColor
  482. Return New MyColor With {.A = Math.Round(col.A, w), .R = Math.Round(col.R, w), .G = Math.Round(col.G, w), .B = Math.Round(col.B, w)}
  483. End Function
  484. ''' <summary>
  485. ''' 获取两数间的百分比。小数点精确到 6 位。
  486. ''' </summary>
  487. ''' <returns></returns>
  488. ''' <remarks></remarks>
  489. Public Function MathPercent(ValueA As Double, ValueB As Double, Percent As Double) As Double
  490. Return Math.Round(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决 Double 计算错误
  491. End Function
  492. ''' <summary>
  493. ''' 获取两颜色间的百分比,根据 RGB 计算。小数点精确到 6 位。
  494. ''' </summary>
  495. Public Function MathPercent(ValueA As MyColor, ValueB As MyColor, Percent As Double) As MyColor
  496. Return MathRound(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决Double计算错误
  497. End Function
  498. ''' <summary>
  499. ''' 将数值限定在某个范围内。
  500. ''' </summary>
  501. Public Function MathRange(value As Double, min As Double, max As Double) As Double
  502. Return Math.Max(min, Math.Min(max, value))
  503. End Function
  504. ''' <summary>
  505. ''' 符号函数。
  506. ''' </summary>
  507. Public Function MathSgn(Value As Double) As Integer
  508. If Value = 0 Then
  509. Return 0
  510. ElseIf Value > 0 Then
  511. Return 1
  512. Else
  513. Return -1
  514. End If
  515. End Function
  516. #End Region
  517. #Region "文件"
  518. '注册表
  519. ''' <summary>
  520. ''' 重命名一个注册表子键。不可用于包含子键的子键。
  521. ''' </summary>
  522. Public Sub RegRename(parentKey As Microsoft.Win32.RegistryKey, subKeyName As String, newSubKeyName As String)
  523. If parentKey.GetSubKeyNames().Contains(newSubKeyName) Then parentKey.DeleteSubKeyTree(newSubKeyName, False)
  524. Dim SourceKey As Microsoft.Win32.RegistryKey = parentKey.OpenSubKey(subKeyName)
  525. If IsNothing(SourceKey) Then Exit Sub '没有目标项
  526. Dim NewKey As Microsoft.Win32.RegistryKey = parentKey.CreateSubKey(newSubKeyName)
  527. If SourceKey.GetSubKeyNames().Length > 0 Then Throw New NotSupportedException("不支持对包含子键的子键进行重命名:" & SourceKey.GetSubKeyNames()(0) & "。")
  528. For Each valueName As String In SourceKey.GetValueNames()
  529. Dim objValue As Object = SourceKey.GetValue(valueName)
  530. Dim valKind As Microsoft.Win32.RegistryValueKind = SourceKey.GetValueKind(valueName)
  531. NewKey.SetValue(valueName, objValue, valKind)
  532. Next
  533. parentKey.DeleteSubKeyTree(subKeyName, False)
  534. End Sub
  535. ''' <summary>
  536. ''' 读取程序所属注册表。
  537. ''' </summary>
  538. Public Function ReadReg(Key As String, Optional DefaultValue As String = "") As String
  539. Try
  540. Dim parentKey As Microsoft.Win32.RegistryKey, softKey As Microsoft.Win32.RegistryKey
  541. parentKey = My.Computer.Registry.CurrentUser
  542. softKey = parentKey.OpenSubKey("Software\PCL", True)
  543. If softKey Is Nothing Then
  544. ReadReg = DefaultValue '不存在则返回默认值
  545. Else
  546. Dim readValue As New Text.StringBuilder
  547. readValue.AppendLine(softKey.GetValue(Key))
  548. Dim value = readValue.ToString.Replace(vbCrLf, "") '去除莫名的回车
  549. Return If(value = "", DefaultValue, value) '错误则返回默认值
  550. End If
  551. Catch ex As Exception
  552. Log(ex, "读取注册表出错:" & Key, LogLevel.Hint)
  553. Return DefaultValue
  554. End Try
  555. End Function
  556. ''' <summary>
  557. ''' 写入程序所属注册表。
  558. ''' </summary>
  559. Public Sub WriteReg(Key As String, Value As String, Optional ShowException As Boolean = False)
  560. Try
  561. Dim parentKey As Microsoft.Win32.RegistryKey, softKey As Microsoft.Win32.RegistryKey
  562. parentKey = My.Computer.Registry.CurrentUser
  563. softKey = parentKey.OpenSubKey("Software\PCL", True)
  564. If softKey Is Nothing Then softKey = parentKey.CreateSubKey("Software\PCL") '如果不存在就创建
  565. softKey.SetValue(Key, Value)
  566. Catch ex As Exception
  567. Log(ex, "写入注册表出错:" & Key, If(ShowException, LogLevel.Hint, LogLevel.Developer))
  568. If ShowException Then Throw '如果显示错误就丢一个
  569. End Try
  570. End Sub
  571. 'Ini 文件
  572. Private Class IniCache
  573. Public FileContent As String = ""
  574. Public KVCache As New Dictionary(Of String, String)
  575. End Class
  576. Private ReadOnly IniCacheList As New Dictionary(Of String, IniCache)
  577. ''' <summary>
  578. ''' 清除某 Ini 文件的运行时缓存。
  579. ''' </summary>
  580. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  581. Public Sub IniClearCache(FileName As String)
  582. '还原文件路径
  583. If Not FileName.Contains(":\") Then FileName = Path & "PCL\" & FileName & ".ini"
  584. '检索缓存
  585. If IniCacheList.ContainsKey(FileName) Then IniCacheList.Remove(FileName)
  586. End Sub
  587. ''' <summary>
  588. ''' 获取 Ini 文件内容,这可能会使用到缓存。
  589. ''' </summary>
  590. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  591. Private Function IniGetContent(FileName As String) As IniCache
  592. Try
  593. '还原文件路径
  594. If Not FileName.Contains(":\") Then FileName = Path & "PCL\" & FileName & ".ini"
  595. '检索缓存
  596. If IniCacheList.ContainsKey(FileName) Then
  597. '返回缓存中的信息
  598. Dim Cache As New IniCache
  599. IniCacheList.TryGetValue(FileName, Cache)
  600. Return Cache '防止ByRef导致缓存变更
  601. Else
  602. Dim Ini As IniCache
  603. If File.Exists(FileName) Then
  604. '返回文件信息并且记入缓存
  605. Dim Cache As String = (vbCrLf & ReadFile(FileName) & vbCrLf).Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr, vbCrLf).Replace(vbCrLf & vbCrLf, vbCrLf).Replace(vbNullChar, "")
  606. Ini = New IniCache With {.FileContent = Cache}
  607. Else
  608. '返回空文件信息
  609. Ini = New IniCache With {.FileContent = ""}
  610. End If
  611. If Not IniCacheList.ContainsKey(FileName) Then IniCacheList.Add(FileName, Ini) '避免多线程异步执行此方法时造成多次添加项
  612. Return Ini
  613. End If
  614. Catch ex As Exception
  615. Log(ex, "读取文件失败:" & FileName, LogLevel.Hint)
  616. Return New IniCache With {.FileContent = ""}
  617. End Try
  618. End Function
  619. ''' <summary>
  620. ''' 读取Ini文件,这可能会使用到缓存。
  621. ''' </summary>
  622. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  623. ''' <param name="Key">键。</param>
  624. ''' <param name="DefaultValue">没有找到键时返回的默认值。</param>
  625. Public Function ReadIni(FileName As String, Key As String, Optional DefaultValue As String = "") As String
  626. Try
  627. '获取目前文件
  628. Dim NowIni As IniCache = IniGetContent(FileName)
  629. If IsNothing(NowIni) Then Return DefaultValue
  630. '使用缓存
  631. If NowIni.KVCache.ContainsKey(Key) Then Return If(NowIni.KVCache(Key), DefaultValue)
  632. '没有缓存,读取文件
  633. If NowIni.FileContent.Contains(vbCrLf & Key & ":") Then
  634. Dim Ret As String = Mid(NowIni.FileContent, NowIni.FileContent.IndexOf(vbCrLf & Key & ":") + 3)
  635. Ret = If(Ret.Contains(vbCrLf), Mid(Ret, 1, Ret.IndexOf(vbCrLf)), Ret).Replace(Key & ":", "")
  636. NowIni.KVCache.Add(Key, If(Ret = vbLf, "", Ret))
  637. Return If(Ret = vbLf, "", Ret)
  638. Else
  639. Return DefaultValue
  640. End If
  641. Catch ex As Exception
  642. '读取失败
  643. Return DefaultValue
  644. End Try
  645. End Function
  646. ''' <summary>
  647. ''' 写入ini文件,这会更新缓存。
  648. ''' </summary>
  649. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  650. ''' <param name="Key">键。</param>
  651. ''' <param name="Value">值。</param>
  652. ''' <remarks></remarks>
  653. Public Sub WriteIni(FileName As String, Key As String, Value As String)
  654. Try
  655. '还原文件路径
  656. If Not FileName.Contains(":\") Then FileName = Path & "PCL\" & FileName & ".ini"
  657. If IsNothing(Value) Then Value = ""
  658. Value = Value.Replace(vbCrLf, "")
  659. '创建文件夹
  660. If Not Directory.Exists(GetPathFromFullPath(FileName)) Then Directory.CreateDirectory(GetPathFromFullPath(FileName))
  661. '获取目前文件
  662. Dim NowFile As String = IniGetContent(FileName).FileContent
  663. If Not NowFile.EndsWith(vbCrLf) Then NowFile += vbCrLf
  664. '如果值一样就不处理
  665. If NowFile.Contains(vbCrLf & Key & ":" & Value & vbCrLf) Then Exit Sub
  666. '处理文件
  667. Dim FindResult As String = ReadIni(FileName, Key)
  668. If FindResult = "" AndAlso Not NowFile.Contains(vbCrLf & Key & ":") Then
  669. '不存在这个键
  670. NowFile = NowFile & vbCrLf & Key & ":" & Value & vbCrLf
  671. Else
  672. '存在这个键
  673. NowFile = NowFile.Replace(vbCrLf & Key & ":" & FindResult & vbCrLf, vbCrLf & Key & ":" & Value & vbCrLf)
  674. End If
  675. WriteFile(FileName, NowFile)
  676. '刷新目前缓存
  677. IniCacheList(FileName).FileContent = NowFile
  678. IniCacheList(FileName).KVCache.Remove(Key)
  679. IniCacheList(FileName).KVCache.Add(Key, Value)
  680. Catch ex As Exception
  681. Log(ex, "写入文件失败:" & FileName & "/" & Key & ": " & Value)
  682. End Try
  683. End Sub
  684. '路径处理
  685. ''' <summary>
  686. ''' 从文件路径或者 Url 获取不包含文件名的路径,或获取文件夹的父文件夹路径。不包含路径将会抛出异常。
  687. ''' </summary>
  688. Public Function GetPathFromFullPath(FilePath As String) As String
  689. If Not (FilePath.Contains("\") OrElse FilePath.Contains("/")) Then Throw New Exception("不包含路径:" & FilePath)
  690. If FilePath.EndsWith("\") OrElse FilePath.EndsWith("/") Then
  691. '是文件夹路径
  692. Dim IsRight As Boolean = FilePath.EndsWith("\")
  693. FilePath = Left(FilePath, Len(FilePath) - 1)
  694. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"})) & If(IsRight, "\", "/")
  695. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  696. Else
  697. '是文件路径
  698. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"}) + 1)
  699. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  700. End If
  701. End Function
  702. ''' <summary>
  703. ''' 从文件路径或者 Url 获取不包含路径的文件名。不包含文件名将会抛出异常。
  704. ''' </summary>
  705. Public Function GetFileNameFromPath(FilePath As String) As String
  706. If FilePath.EndsWith("\") OrElse FilePath.EndsWith("/") Then Throw New Exception("不包含文件名:" & FilePath)
  707. If Not (FilePath.Contains("\") OrElse FilePath.Contains("/")) Then Return FilePath
  708. If FilePath.Contains("?") Then FilePath = Left(FilePath, FilePath.LastIndexOf("?")) '去掉网络参数后的 ?
  709. GetFileNameFromPath = Mid(FilePath, FilePath.LastIndexOfAny({"\", "/"}) + 2)
  710. If GetFileNameFromPath = "" Then Throw New Exception("不包含文件名:" & FilePath)
  711. End Function
  712. ''' <summary>
  713. ''' 从文件路径或者 Url 获取不包含路径与扩展名的文件名。不包含文件名将会抛出异常。
  714. ''' </summary>
  715. Public Function GetFileNameWithoutExtentionFromPath(FilePath As String) As String
  716. Dim Name As String = GetFileNameFromPath(FilePath)
  717. If Name.Contains(".") Then
  718. Return Name.Substring(0, Name.LastIndexOf("."))
  719. Else
  720. Return Name
  721. End If
  722. End Function
  723. ''' <summary>
  724. ''' 从文件夹路径获取文件夹名。
  725. ''' </summary>
  726. Public Function GetFolderNameFromPath(FolderPath As String) As String
  727. If FolderPath.EndsWith(":\") OrElse FolderPath.EndsWith(":\\") Then Return FolderPath.Substring(0, 1)
  728. If FolderPath.EndsWith("\") OrElse FolderPath.EndsWith("/") Then FolderPath = Left(FolderPath, FolderPath.Length - 1)
  729. Return GetFileNameFromPath(FolderPath)
  730. End Function
  731. '读取、写入、复制文件
  732. Public Sub CopyFile(FromPath As String, ToPath As String)
  733. Try
  734. '还原文件路径
  735. If Not FromPath.Contains(":\") Then FromPath = Path & FromPath
  736. If Not ToPath.Contains(":\") Then ToPath = Path & ToPath
  737. '如果复制同一个文件则跳过
  738. If FromPath = ToPath Then Exit Sub
  739. '读取文件内容
  740. Dim FileBytes As Byte()
  741. Using ReadStream As New FileStream(FromPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) '支持读取使用中的文件
  742. ReDim FileBytes(ReadStream.Length - 1)
  743. ReadStream.Read(FileBytes, 0, ReadStream.Length)
  744. End Using
  745. '写入文件内容
  746. WriteFile(ToPath, FileBytes)
  747. Catch ex As Exception
  748. Throw New Exception("复制文件出错:" & FromPath & " -> " & ToPath, ex)
  749. End Try
  750. End Sub
  751. ''' <summary>
  752. ''' 读取文件,如果失败则返回空字符串。
  753. ''' </summary>
  754. ''' <param name="FilePath">文件完整或相对路径。</param>
  755. Public Function ReadFile(FilePath As String, Optional Encoding As Encoding = Nothing) As String
  756. Try
  757. '还原文件路径
  758. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  759. If File.Exists(FilePath) Then
  760. Dim FileBytes As Byte()
  761. Using ReadStream As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) '支持读取使用中的文件
  762. ReDim FileBytes(ReadStream.Length - 1)
  763. ReadStream.Read(FileBytes, 0, ReadStream.Length)
  764. End Using
  765. ReadFile = If(Encoding Is Nothing, DecodeBytes(FileBytes), Encoding.GetString(FileBytes))
  766. Else
  767. Log("[System] 欲读取的文件不存在,已返回空字符串:" & FilePath)
  768. Return ""
  769. End If
  770. Catch ex As Exception
  771. Log(ex, "读取文件出错:" & FilePath)
  772. Return ""
  773. End Try
  774. End Function
  775. ''' <summary>
  776. ''' 读取流中的所有文本。
  777. ''' </summary>
  778. Public Function ReadFile(Stream As Stream, Optional Encoding As Encoding = Nothing) As String
  779. Try
  780. Dim srcBuf As Byte() = New Byte(16384) {}
  781. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  782. Dim Result As New List(Of Byte)
  783. While DataCount > 0
  784. If DataCount > 0 Then Result.AddRange(srcBuf.ToList.GetRange(0, DataCount))
  785. DataCount = Stream.Read(srcBuf, 0, 16384)
  786. End While
  787. Dim Bts = Result.ToArray
  788. Return If(Encoding, GetEncoding(Bts)).GetString(Bts)
  789. Catch ex As Exception
  790. Log(ex, "读取流出错")
  791. Return ""
  792. End Try
  793. End Function
  794. ''' <summary>
  795. ''' 写入文件。
  796. ''' </summary>
  797. ''' <param name="FilePath">文件完整或相对路径。</param>
  798. ''' <param name="Text">文件内容。</param>
  799. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  800. Public Function WriteFile(FilePath As String, Text As String, Optional Append As Boolean = False, Optional Encoding As Encoding = Nothing) As Boolean
  801. Try
  802. '还原文件路径
  803. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  804. '确保目录存在
  805. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  806. '写入文件
  807. If File.Exists(FilePath) Then
  808. '如果文件存在,刷新目前文件
  809. Using writer As New StreamWriter(FilePath, Append, If(Encoding, GetEncoding(FilePath)))
  810. writer.Write(Text)
  811. writer.Flush()
  812. writer.Close()
  813. End Using
  814. Else
  815. '如果文件不存在,则新建并写入
  816. File.WriteAllText(FilePath, Text, If(Encoding, New UTF8Encoding(False)))
  817. End If
  818. Return True
  819. Catch ex As Exception
  820. Log(ex, "写入文件时出错:" & FilePath)
  821. Return False
  822. End Try
  823. End Function
  824. ''' <summary>
  825. ''' 写入文件。
  826. ''' </summary>
  827. ''' <param name="FilePath">文件完整或相对路径。</param>
  828. ''' <param name="Content">文件内容。</param>
  829. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  830. Public Function WriteFile(FilePath As String, Content As Byte(), Optional Append As Boolean = False) As Boolean
  831. Try
  832. '还原文件路径
  833. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  834. '确保目录存在
  835. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  836. '写入文件
  837. File.WriteAllBytes(FilePath, Content)
  838. Return True
  839. Catch ex As Exception
  840. Log(ex, "写入文件时出错:" & FilePath)
  841. Return False
  842. End Try
  843. End Function
  844. ''' <summary>
  845. ''' 将流写入文件。
  846. ''' </summary>
  847. ''' <param name="FilePath">文件完整或相对路径。</param>
  848. Public Function WriteFile(FilePath As String, Stream As Stream) As Boolean
  849. Try
  850. '还原文件路径
  851. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  852. '确保目录存在
  853. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  854. '读取流
  855. Using fs As New FileStream(FilePath, FileMode.Create, FileAccess.Write)
  856. Dim srcBuf As Byte() = New Byte(16384) {}
  857. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  858. While DataCount > 0
  859. If DataCount > 0 Then fs.Write(srcBuf, 0, DataCount)
  860. DataCount = Stream.Read(srcBuf, 0, 16384)
  861. End While
  862. fs.Close()
  863. End Using
  864. Return True
  865. Catch ex As Exception
  866. Log(ex, "保存流出错")
  867. Return False
  868. End Try
  869. End Function
  870. '文件编码
  871. ''' <summary>
  872. ''' 获取文件编码。
  873. ''' </summary>
  874. ''' <param name="FilePath">文件完整或相对路径。</param>
  875. Public Function GetEncoding(FilePath As String) As Encoding
  876. '还原文件路径
  877. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  878. '获取编码
  879. GetEncoding = GetEncoding(File.ReadAllBytes(FilePath))
  880. End Function
  881. ''' <summary>
  882. ''' 获取 Bytes 的编码。
  883. ''' </summary>
  884. Public Function GetEncoding(Bytes As Byte()) As Encoding
  885. Dim Length As Integer = Bytes.Count
  886. If Length <= 2 Then Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  887. '根据 BOM 判断编码
  888. If Bytes(0) >= &HEF Then
  889. '有 BOM 类型
  890. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  891. Return New UTF8Encoding(True) '带 BOM 的 UTF8
  892. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  893. Return Encoding.BigEndianUnicode
  894. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  895. Return Encoding.Unicode
  896. Else
  897. Return Encoding.GetEncoding("GB18030")
  898. End If
  899. End If
  900. '无 BOM 文件:GB18030(ANSI)或 UTF8
  901. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  902. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  903. If UTF8.Contains(ErrorChar) Then
  904. Return Encoding.GetEncoding("GB18030")
  905. Else
  906. Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  907. End If
  908. End Function
  909. ''' <summary>
  910. ''' 解码 Bytes。
  911. ''' </summary>
  912. Public Function DecodeBytes(Bytes As Byte()) As String
  913. Dim Length As Integer = Bytes.Length
  914. If Length < 3 Then Return Encoding.UTF8.GetString(Bytes)
  915. '根据 BOM 判断编码
  916. If Bytes(0) >= &HEF Then
  917. '有 BOM 类型
  918. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  919. Return Encoding.UTF8.GetString(Bytes, 3, Length - 3)
  920. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  921. Return Encoding.BigEndianUnicode.GetString(Bytes, 3, Length - 3)
  922. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  923. Return Encoding.Unicode.GetString(Bytes, 3, Length - 3)
  924. Else
  925. Return Encoding.GetEncoding("GB18030").GetString(Bytes, 3, Length - 3)
  926. End If
  927. End If
  928. '无 BOM 文件:GB18030(ANSI)或 UTF8
  929. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  930. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  931. If UTF8.Contains(ErrorChar) Then
  932. Return Encoding.GetEncoding("GB18030").GetString(Bytes)
  933. Else
  934. Return UTF8
  935. End If
  936. End Function
  937. '对话框
  938. ''' <summary>
  939. ''' 弹出保存对话框并且要求保存位置,返回用户输入的完整路径。
  940. ''' </summary>
  941. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  942. ''' <param name="Title">弹窗的标题。</param>
  943. ''' <param name="FileName">默认的文件名。</param>
  944. Public Function SelectAs(Title As String, FileName As String, Optional FileFilter As String = Nothing, Optional DefaultDir As String = Nothing) As String
  945. Using fileDialog As New Forms.SaveFileDialog
  946. fileDialog.AddExtension = True
  947. fileDialog.AutoUpgradeEnabled = True
  948. fileDialog.Title = Title
  949. fileDialog.FileName = FileName
  950. If FileFilter IsNot Nothing Then fileDialog.Filter = FileFilter
  951. If DefaultDir IsNot Nothing Then fileDialog.InitialDirectory = DefaultDir
  952. fileDialog.ShowDialog()
  953. SelectAs = If(fileDialog.FileName.Contains(":\"), fileDialog.FileName, "")
  954. Log("[UI] 选择文件返回:" & SelectAs)
  955. End Using
  956. End Function
  957. ''' <summary>
  958. ''' 弹出选取文件对话框并且要求选取文件。
  959. ''' </summary>
  960. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  961. ''' <param name="Title">弹窗的标题。</param>
  962. Public Function SelectFile(FileFilter As String, Title As String) As String
  963. Using fileDialog As New Forms.OpenFileDialog
  964. fileDialog.AddExtension = True
  965. fileDialog.AutoUpgradeEnabled = True
  966. fileDialog.CheckFileExists = True
  967. fileDialog.Filter = FileFilter
  968. fileDialog.Multiselect = False
  969. fileDialog.Title = Title
  970. fileDialog.ValidateNames = True
  971. fileDialog.ShowDialog()
  972. SelectFile = fileDialog.FileName
  973. Log("[UI] 选择文件返回:" & SelectFile)
  974. End Using
  975. End Function
  976. ''' <summary>
  977. ''' 弹出选取文件夹对话框并且要求选取文件夹。如果没有选择就返回空字符串。
  978. ''' </summary>
  979. Public Function SelectFolder(Optional Title As String = "选择文件夹") As String
  980. Dim folderDialog As New Ookii.Dialogs.Wpf.VistaFolderBrowserDialog With {.ShowNewFolderButton = True, .RootFolder = Environment.SpecialFolder.Desktop, .Description = Title, .UseDescriptionForTitle = True}
  981. folderDialog.ShowDialog()
  982. SelectFolder = If(String.IsNullOrEmpty(folderDialog.SelectedPath), "", folderDialog.SelectedPath & If(folderDialog.SelectedPath.EndsWith("\"), "", "\"))
  983. Log("[UI] 选择文件夹返回:" & SelectFolder)
  984. End Function
  985. '文件校验
  986. ''' <summary>
  987. ''' 检查是否拥有某一文件夹的 I/O 权限。如果文件夹不存在,会返回 False。
  988. ''' </summary>
  989. Public Function CheckPermission(Path As String) As Boolean
  990. Try
  991. If Path = "" Then Return False
  992. If Not Path.EndsWith("\") Then Path += "\"
  993. If Path.EndsWith(":\System Volume Information\") OrElse Path.EndsWith(":\$RECYCLE.BIN\") Then Return False
  994. If Not Directory.Exists(Path) Then Return False
  995. Dim FileName As String = "CheckPermission" & GetUuid()
  996. If File.Exists(Path & FileName) Then File.Delete(Path & FileName)
  997. File.Create(Path & FileName).Dispose()
  998. File.Delete(Path & FileName)
  999. Return True
  1000. Catch ex As Exception
  1001. Log(ex, "没有对文件夹 " & Path & " 的权限,请尝试以管理员权限运行 PCL")
  1002. Return False
  1003. End Try
  1004. End Function
  1005. ''' <summary>
  1006. ''' 检查是否拥有某一文件夹的 I/O 权限。如果出错,则抛出异常。
  1007. ''' </summary>
  1008. Public Sub CheckPermissionWithException(Path As String)
  1009. If String.IsNullOrWhiteSpace(Path) Then Throw New ArgumentNullException("文件夹名不能为空!")
  1010. If Not Path.EndsWith("\") Then Path += "\"
  1011. If Not Directory.Exists(Path) Then Throw New DirectoryNotFoundException("文件夹不存在!")
  1012. If File.Exists(Path & "CheckPermission") Then File.Delete(Path & "CheckPermission")
  1013. File.Create(Path & "CheckPermission").Dispose()
  1014. File.Delete(Path & "CheckPermission")
  1015. End Sub
  1016. ''' <summary>
  1017. ''' 获取文件 MD5,若失败则返回空字符串。
  1018. ''' </summary>
  1019. Public Function GetAuthMD5(FilePath As String) As String
  1020. Dim Retry As Boolean = False
  1021. Re:
  1022. Try
  1023. '获取 MD5
  1024. Dim Result As New StringBuilder()
  1025. Dim File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1026. Dim MD5 As MD5 = New MD5CryptoServiceProvider()
  1027. Dim Retval As Byte() = MD5.ComputeHash(File)
  1028. File.Close()
  1029. For i = 0 To Retval.Length - 1
  1030. Result.Append(Retval(i).ToString("x2"))
  1031. Next
  1032. Return Result.ToString
  1033. Catch ex As Exception
  1034. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1035. Log(ex, "获取文件 MD5 失败:" & FilePath)
  1036. Return ""
  1037. Else
  1038. Retry = True
  1039. Log(ex, "获取文件 MD5 可重试失败:" & FilePath, LogLevel.Normal)
  1040. Thread.Sleep(RandomInteger(200, 500))
  1041. GoTo Re
  1042. End If
  1043. End Try
  1044. End Function
  1045. ''' <summary>
  1046. ''' 获取文件 SHA256,若失败则返回空字符串。
  1047. ''' </summary>
  1048. Public Function GetAuthSHA256(FilePath As String) As String
  1049. Dim Retry As Boolean = False
  1050. Re:
  1051. Try
  1052. ''检测该文件是否在下载中,若在下载则放弃检测
  1053. 'If IgnoreOnDownloading AndAlso NetManage.Files.ContainsKey(FilePath) AndAlso NetManage.Files(FilePath).State <= NetState.Merge Then Return ""
  1054. '获取 SHA256
  1055. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1056. Dim sha1 As SHA256 = New SHA256CryptoServiceProvider()
  1057. Dim retval As Byte() = sha1.ComputeHash(file)
  1058. file.Close()
  1059. Dim Result As New StringBuilder()
  1060. For i As Integer = 0 To retval.Length - 1
  1061. Result.Append(retval(i).ToString("x2"))
  1062. Next
  1063. Return Result.ToString
  1064. Catch ex As Exception
  1065. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1066. Log(ex, "获取文件 SHA256 失败:" & FilePath)
  1067. Return ""
  1068. Else
  1069. Retry = True
  1070. Log(ex, "获取文件 SHA256 可重试失败:" & FilePath, LogLevel.Normal)
  1071. Thread.Sleep(RandomInteger(200, 500))
  1072. GoTo Re
  1073. End If
  1074. End Try
  1075. End Function
  1076. ''' <summary>
  1077. ''' 获取文件 SHA1,若失败则返回空字符串。
  1078. ''' </summary>
  1079. Public Function GetAuthSHA1(FilePath As String) As String
  1080. Dim Retry As Boolean = False
  1081. Re:
  1082. Try
  1083. ''检测该文件是否在下载中,若在下载则放弃检测
  1084. 'If IgnoreOnDownloading AndAlso NetManage.Files.ContainsKey(FilePath) AndAlso NetManage.Files(FilePath).State <= NetState.Merge Then Return ""
  1085. '获取 SHA1
  1086. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1087. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1088. Dim retval As Byte() = sha1.ComputeHash(file)
  1089. file.Close()
  1090. Dim Result As New StringBuilder()
  1091. For i As Integer = 0 To retval.Length - 1
  1092. Result.Append(retval(i).ToString("x2"))
  1093. Next
  1094. Return Result.ToString
  1095. Catch ex As Exception
  1096. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1097. Log(ex, "获取文件 SHA1 失败:" & FilePath)
  1098. Return ""
  1099. Else
  1100. Retry = True
  1101. Log(ex, "获取文件 SHA1 可重试失败:" & FilePath, LogLevel.Normal)
  1102. Thread.Sleep(RandomInteger(200, 500))
  1103. GoTo Re
  1104. End If
  1105. End Try
  1106. End Function
  1107. ''' <summary>
  1108. ''' 获取流 SHA1,若失败则返回空字符串。
  1109. ''' </summary>
  1110. Public Function GetAuthSHA1(Stream As Stream) As String
  1111. Try
  1112. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1113. Dim retval As Byte() = sha1.ComputeHash(Stream)
  1114. Dim Result As New StringBuilder()
  1115. For i As Integer = 0 To retval.Length - 1
  1116. Result.Append(retval(i).ToString("x2"))
  1117. Next
  1118. Return Result.ToString
  1119. Catch ex As Exception
  1120. Log(ex, "获取流 SHA1 失败")
  1121. Return ""
  1122. End Try
  1123. End Function
  1124. ''' <summary>
  1125. ''' 文件的校验规则。
  1126. ''' </summary>
  1127. Public Class FileChecker
  1128. ''' <summary>
  1129. ''' 文件的准确大小。
  1130. ''' </summary>
  1131. Public ActualSize As Long = -1
  1132. ''' <summary>
  1133. ''' 文件的最小大小。
  1134. ''' </summary>
  1135. Public MinSize As Long = -1
  1136. ''' <summary>
  1137. ''' 文件的 MD5、SHA1 或 SHA256。会根据输入字符串的长度自动判断种类。
  1138. ''' </summary>
  1139. Public Hash As String = Nothing
  1140. ''' <summary>
  1141. ''' 是否可以使用已经存在的文件。
  1142. ''' </summary>
  1143. Public CanUseExistsFile As Boolean = True
  1144. ''' <summary>
  1145. ''' 是否为 Json 文件。
  1146. ''' </summary>
  1147. Public IsJson As Boolean = False
  1148. Public Sub New(Optional MinSize As Long = -1, Optional ActualSize As Long = -1, Optional Hash As String = Nothing, Optional CanUseExistsFile As Boolean = True, Optional IsJson As Boolean = False)
  1149. Me.ActualSize = ActualSize
  1150. Me.MinSize = MinSize
  1151. Me.Hash = Hash
  1152. Me.CanUseExistsFile = CanUseExistsFile
  1153. Me.IsJson = IsJson
  1154. End Sub
  1155. ''' <summary>
  1156. ''' 检查文件。若成功则返回 Nothing,失败则返回错误的描述文本,描述文本不以句号结尾。不会抛出错误。
  1157. ''' </summary>
  1158. Public Function Check(LocalPath As String) As String
  1159. Try
  1160. Dim Info As New FileInfo(LocalPath)
  1161. If Not Info.Exists Then Return "文件不存在:" & LocalPath
  1162. Dim FileSize As Long = Info.Length
  1163. If ActualSize >= 0 AndAlso ActualSize <> FileSize Then Return "文件大小应为 " & ActualSize & " B,实际为 " & FileSize & " B"
  1164. If MinSize >= 0 AndAlso MinSize > FileSize Then Return "文件大小应大于 " & MinSize & " B,实际为 " & FileSize & " B"
  1165. If Not String.IsNullOrEmpty(Hash) Then
  1166. If Hash.Length < 35 Then 'MD5
  1167. If Hash <> GetAuthMD5(LocalPath) Then Return "文件 MD5 应为 " & Hash & ",实际为 " & GetAuthMD5(LocalPath)
  1168. ElseIf Hash.Length = 64 Then 'SHA256
  1169. If Hash <> GetAuthSHA256(LocalPath) Then Return "文件 SHA256 应为 " & Hash & ",实际为 " & GetAuthSHA256(LocalPath)
  1170. Else 'SHA1 (40)
  1171. If Hash <> GetAuthSHA1(LocalPath) Then Return "文件 SHA1 应为 " & Hash & ",实际为 " & GetAuthSHA1(LocalPath)
  1172. End If
  1173. End If
  1174. If IsJson Then
  1175. Dim Content As String = ReadFile(LocalPath)
  1176. If Content = "" Then Throw New Exception("读取到的文件为空")
  1177. Try
  1178. GetJson(Content)
  1179. Catch ex As Exception
  1180. Throw New Exception("不是有效的 Json 文件", ex)
  1181. End Try
  1182. End If
  1183. Return Nothing
  1184. Catch ex As Exception
  1185. Log(ex, "检查文件出错")
  1186. Return GetExceptionSummary(ex)
  1187. End Try
  1188. End Function
  1189. End Class
  1190. ''' <summary>
  1191. ''' 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  1192. ''' 会尝试创建,但不会清空目标文件夹。
  1193. ''' 成功返回 True,并非压缩文件或失败返回 False。
  1194. ''' </summary>
  1195. Public Function ExtractFile(CompressFilePath As String, DestDirectory As String, Optional Encode As Encoding = Nothing) As Boolean
  1196. Try
  1197. Directory.CreateDirectory(DestDirectory)
  1198. If CompressFilePath.EndsWith(".zip") OrElse CompressFilePath.EndsWith(".jar") Then
  1199. '以 zip 方式解压
  1200. ZipFile.ExtractToDirectory(CompressFilePath, DestDirectory, If(Encode, Encoding.GetEncoding("GB18030")))
  1201. Return True
  1202. ElseIf CompressFilePath.EndsWith(".gz") Then
  1203. '以 gz 方式解压
  1204. Dim stream As New GZipStream(New FileStream(CompressFilePath, FileMode.Open, FileAccess.ReadWrite), CompressionMode.Decompress)
  1205. Dim decompressedFile As New FileStream(DestDirectory & GetFileNameFromPath(CompressFilePath).ToLower.Replace(".tar", "").Replace(".gz", ""), FileMode.OpenOrCreate, FileAccess.Write)
  1206. Dim data As Integer = stream.ReadByte()
  1207. While data <> -1
  1208. decompressedFile.WriteByte(data)
  1209. data = stream.ReadByte()
  1210. End While
  1211. decompressedFile.Close()
  1212. stream.Close()
  1213. Return True
  1214. Else
  1215. Return False
  1216. End If
  1217. Catch ex As Exception
  1218. Log(ex, "尝试解压文件失败")
  1219. Return False
  1220. End Try
  1221. End Function
  1222. ''' <summary>
  1223. ''' 删除文件夹。失败会抛出异常。
  1224. ''' </summary>
  1225. Public Sub DeleteDirectory(Path As String, Optional IgnoreIssue As Boolean = False)
  1226. If Not Directory.Exists(Path) Then Exit Sub
  1227. Dim Temp As String()
  1228. Temp = Directory.GetFiles(Path)
  1229. For Each str As String In Temp
  1230. Try
  1231. File.Delete(str)
  1232. Catch ex As Exception
  1233. If IgnoreIssue Then
  1234. Log(ex, "删除单个文件可忽略地失败")
  1235. Else
  1236. Throw
  1237. End If
  1238. End Try
  1239. Next
  1240. Temp = Directory.GetDirectories(Path)
  1241. For Each str As String In Temp
  1242. DeleteDirectory(str)
  1243. Next
  1244. Try
  1245. Directory.Delete(Path, True)
  1246. Catch ex As Exception
  1247. If IgnoreIssue Then
  1248. Log(ex, "删除单个文件夹可忽略地失败")
  1249. Else
  1250. Throw
  1251. End If
  1252. End Try
  1253. '这个也不靠谱,目录不是空的警告
  1254. 'My.Computer.FileSystem.DeleteDirectory(Path, FileIO.DeleteDirectoryOption.DeleteAllContents)
  1255. End Sub
  1256. ''' <summary>
  1257. ''' 复制文件夹,失败会抛出异常。
  1258. ''' </summary>
  1259. Public Sub CopyDirectory(FromPath As String, ToPath As String)
  1260. For Each File In EnumerateFiles(FromPath)
  1261. CopyFile(File.FullName, File.FullName.Replace(FromPath, ToPath))
  1262. Next
  1263. End Sub
  1264. ''' <summary>
  1265. ''' 遍历文件夹中的所有文件。
  1266. ''' </summary>
  1267. Public Function EnumerateFiles(Directory As String) As List(Of FileInfo)
  1268. Return New DirectoryInfo(Directory).EnumerateFiles("*", SearchOption.AllDirectories).ToList
  1269. End Function
  1270. #End Region
  1271. #Region "文本"
  1272. Public vbLQ As Char = Convert.ToChar(8220)
  1273. Public vbRQ As Char = Convert.ToChar(8221)
  1274. ''' <summary>
  1275. ''' 提取 Exception 的具体描述与堆栈。
  1276. ''' </summary>
  1277. ''' <param name="ShowAllTrace">是否必须显示所有堆栈。通常用于判定堆栈信息。</param>
  1278. Public Function GetExceptionDetail(Ex As Exception, Optional ShowAllTrace As Boolean = False) As String
  1279. If Ex Is Nothing Then Return "无可用错误信息!"
  1280. '获取最底层的异常
  1281. Dim InnerEx As Exception = Ex
  1282. Do Until InnerEx.InnerException Is Nothing
  1283. InnerEx = InnerEx.InnerException
  1284. Loop
  1285. '获取各级错误的描述与堆栈信息
  1286. Dim DescList As New List(Of String)
  1287. Dim StackList As New List(Of String)
  1288. Do Until Ex Is Nothing
  1289. DescList.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, vbCrLf))
  1290. If Ex.StackTrace IsNot Nothing Then
  1291. For Each St As String In Ex.StackTrace.Split(vbCrLf)
  1292. If ShowAllTrace OrElse St.ToLower.Contains("pcl") Then StackList.Add(St.Replace(vbCr, String.Empty).Replace(vbLf, String.Empty))
  1293. Next
  1294. End If
  1295. Ex = Ex.InnerException
  1296. Loop
  1297. DescList = DescList.Distinct.ToList
  1298. Dim Desc As String = Join(DescList, vbCrLf & "→ ")
  1299. Dim Stack As String = If(StackList.Count > 0, vbCrLf & Join(StackList, vbCrLf), "")
  1300. '常见错误
  1301. Dim CommonReason As String = Nothing
  1302. If TypeOf InnerEx Is TypeLoadException OrElse TypeOf InnerEx Is MissingMethodException OrElse TypeOf InnerEx Is NotImplementedException OrElse TypeOf InnerEx Is TypeInitializationException Then
  1303. CommonReason = "PCL2 的运行环境存在问题。请尝试重新安装 .NET Framework 4.6.2 然后再试。"
  1304. ElseIf TypeOf InnerEx Is UnauthorizedAccessException Then
  1305. CommonReason = "PCL2 的权限不足。请尝试右键 PCL2,选择以管理员身份运行。"
  1306. ElseIf TypeOf InnerEx Is OutOfMemoryException Then
  1307. CommonReason = "你的电脑运行内存不足,导致 PCL2 无法继续运行。请在关闭一部分不需要的程序后再试。"
  1308. ElseIf {"远程主机强迫关闭了", "远程方已关闭传输流", "未能解析此远程名称", "由于目标计算机积极拒绝",
  1309. "操作已超时", "操作超时", "服务器超时", "连接超时"}.Any(Function(s) Desc.Contains(s)) Then
  1310. CommonReason = "你的网络环境不佳,导致难以连接到服务器。请检查网络,多重试几次,或尝试使用 VPN。"
  1311. End If
  1312. '获取错误类型
  1313. Dim TypeDesc As String = If(InnerEx.GetType.FullName = "System.Exception", "", vbCrLf & "错误类型:" & InnerEx.GetType.FullName)
  1314. '构造输出信息
  1315. If CommonReason Is Nothing Then
  1316. Return Desc & Stack & TypeDesc
  1317. Else
  1318. Dim Result As String = DescList.First & vbCrLf & CommonReason & vbCrLf & "————————————" & vbCrLf
  1319. DescList(0) = "详细错误信息:"
  1320. Return Result & Join(DescList, vbCrLf & "→ ") & Stack & TypeDesc
  1321. End If
  1322. End Function
  1323. ''' <summary>
  1324. ''' 提取 Exception 描述,汇总到一行。
  1325. ''' </summary>
  1326. Public Function GetExceptionSummary(Ex As Exception) As String
  1327. If Ex Is Nothing Then Return "无可用错误信息!"
  1328. '获取最底层的异常
  1329. Dim InnerEx As Exception = Ex
  1330. Do Until InnerEx.InnerException Is Nothing
  1331. InnerEx = InnerEx.InnerException
  1332. Loop
  1333. '获取各级错误的描述
  1334. Dim DescList As New List(Of String)
  1335. Do Until Ex Is Nothing
  1336. DescList.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, " "))
  1337. Ex = Ex.InnerException
  1338. Loop
  1339. DescList = DescList.Distinct.ToList
  1340. '常见错误
  1341. Dim Desc As String = Join(DescList, vbCrLf & "→ ")
  1342. Dim CommonReason As String = Nothing
  1343. If TypeOf InnerEx Is TypeLoadException OrElse TypeOf InnerEx Is MissingMethodException OrElse TypeOf InnerEx Is NotImplementedException OrElse TypeOf InnerEx Is TypeInitializationException Then
  1344. CommonReason = "PCL2 的运行环境存在问题。请尝试重新安装 .NET Framework 4.6.2 然后再试。"
  1345. ElseIf TypeOf InnerEx Is UnauthorizedAccessException Then
  1346. CommonReason = "PCL2 的权限不足。请尝试右键 PCL2,选择以管理员身份运行。"
  1347. ElseIf TypeOf InnerEx Is OutOfMemoryException Then
  1348. CommonReason = "你的电脑运行内存不足,导致 PCL2 无法继续运行。请在关闭一部分不需要的程序后再试。"
  1349. ElseIf {"远程主机强迫关闭了", "远程方已关闭传输流", "操作已超时", "操作超时", "服务器超时", "连接超时"}.Any(Function(s) Desc.Contains(s)) Then
  1350. CommonReason = "你的网络环境不佳,导致难以连接到服务器。请重试,或尝试使用 VPN。"
  1351. End If
  1352. '构造输出信息
  1353. If CommonReason IsNot Nothing Then
  1354. Return DescList.First & ":" & CommonReason
  1355. Else
  1356. DescList.Reverse() '让最深层错误在最左边
  1357. Return Join(DescList, " → ")
  1358. End If
  1359. End Function
  1360. ''' <summary>
  1361. ''' 返回一个枚举对应的字符串。
  1362. ''' </summary>
  1363. ''' <param name="EnumData">一个已经实例化的枚举类型。</param>
  1364. Public Function GetStringFromEnum(EnumData As [Enum]) As String
  1365. Return [Enum].GetName(EnumData.GetType, EnumData)
  1366. End Function
  1367. ''' <summary>
  1368. ''' 将文件大小转化为适合的文本形式,如“1.28 M”。
  1369. ''' </summary>
  1370. ''' <param name="FileSize">以字节为单位的大小表示。</param>
  1371. Public Function GetString(FileSize As Long) As String
  1372. If FileSize < 1000 Then
  1373. 'B 级
  1374. Return FileSize & " B"
  1375. ElseIf FileSize < 1024 * 1000 Then
  1376. 'K 级
  1377. Dim RoundResult As String = Math.Round(FileSize / 1024)
  1378. Return Math.Round(FileSize / 1024, CInt(MathRange(3 - RoundResult.Length, 0, 2))) & " K"
  1379. ElseIf FileSize < 1024 * 1024 * 1000 Then
  1380. 'M 级
  1381. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024)
  1382. Return Math.Round(FileSize / 1024 / 1024, CInt(MathRange(3 - RoundResult.Length, 0, 2))) & " M"
  1383. Else
  1384. 'G 级
  1385. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024 / 1024)
  1386. Return Math.Round(FileSize / 1024 / 1024 / 1024, CInt(MathRange(3 - RoundResult.Length, 0, 2))) & " G"
  1387. End If
  1388. End Function
  1389. ''' <summary>
  1390. ''' 获取 Json 对象。
  1391. ''' </summary>
  1392. Public Function GetJson(Data As String)
  1393. Try
  1394. Return JsonConvert.DeserializeObject(Data, New JsonSerializerSettings With {.DateTimeZoneHandling = DateTimeZoneHandling.Local})
  1395. Catch ex As Exception
  1396. Throw New Exception("格式化 Json 对象失败:" & If(If(Data, "").Length > 10000, Data.Substring(0, 100) & "...", Data))
  1397. End Try
  1398. End Function
  1399. ''' <summary>
  1400. ''' 将字符串统一至某个长度,过短则以 Code 将其右侧填充,过长则截取靠左的指定长度。
  1401. ''' </summary>
  1402. Public Function StrFill(Str As String, Code As String, Length As Byte) As String
  1403. If Str.Length > Length Then Return Mid(Str, 1, Length)
  1404. Return Mid(Str.PadRight(Length, Code), Str.Length + 1) & Str
  1405. End Function
  1406. ''' <summary>
  1407. ''' 将一个小数显示为固定的小数点后位数形式,将向零取整。
  1408. ''' 如 12 保留 2 位则输出 12.00,而 95.678 保留 2 位则输出 95.67。
  1409. ''' </summary>
  1410. Public Function StrFillNum(Num As Double, Length As Integer) As String
  1411. Num = Math.Round(Num, Length, MidpointRounding.AwayFromZero)
  1412. StrFillNum = Num
  1413. If Not StrFillNum.Contains(".") Then Return (StrFillNum & ".").PadRight(StrFillNum.Length + 1 + Length, "0")
  1414. Return StrFillNum.PadRight(StrFillNum.Split(".")(0).Length + 1 + Length, "0")
  1415. End Function
  1416. ''' <summary>
  1417. ''' 移除字符串首尾的标点符号、回车,以及括号中、冒号后的补充说明内容。
  1418. ''' </summary>
  1419. Public Function StrTrim(Str As String, Optional RemoveQuote As Boolean = True)
  1420. If RemoveQuote Then Str = Str.Split("(")(0).Split(":")(0).Split("(")(0).Split(":")(0)
  1421. Return Str.Trim(".", "。", "!", " ", "!", "?", "?", vbCr, vbLf)
  1422. End Function
  1423. ''' <summary>
  1424. ''' 连接字符串。
  1425. ''' </summary>
  1426. Public Function Join(List As ICollection, Split As String) As String
  1427. Dim Builder As New StringBuilder
  1428. Dim LastCount As Integer = List.Count - 1
  1429. For i = 0 To LastCount
  1430. If List(i) IsNot Nothing Then Builder.Append(List(i))
  1431. If i <> LastCount Then Builder.Append(Split)
  1432. Next
  1433. Return Builder.ToString
  1434. End Function
  1435. ''' <summary>
  1436. ''' 获取字符串哈希值。
  1437. ''' </summary>
  1438. Public Function GetHash(Str As String) As ULong
  1439. GetHash = 5381
  1440. For i = 0 To Str.Length - 1
  1441. GetHash = (GetHash << 5) Xor GetHash Xor CType(AscW(Str(i)), ULong)
  1442. Next
  1443. Return GetHash Xor &HA98F501BC684032FUL
  1444. End Function
  1445. ''' <summary>
  1446. ''' 获取字符串 MD5。
  1447. ''' </summary>
  1448. Public Function GetStringMD5(Str As String) As String
  1449. Dim md5Hasher As New MD5CryptoServiceProvider
  1450. Dim hashedDataBytes As Byte()
  1451. hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(Str))
  1452. Dim tmp As New StringBuilder()
  1453. For Each i As Byte In hashedDataBytes
  1454. tmp.Append(i.ToString("x2"))
  1455. Next
  1456. Return tmp.ToString()
  1457. End Function
  1458. ''' <summary>
  1459. ''' 输入 And 字符不会报错的 Val。
  1460. ''' </summary>
  1461. Public Function Val(Str As Object) As Double
  1462. Return If(TypeOf Str Is String AndAlso Str = "&", 0, Conversion.Val(Str))
  1463. End Function
  1464. '转义
  1465. ''' <summary>
  1466. ''' 为字符串进行 XML 转义。
  1467. ''' </summary>
  1468. Public Function EscapeXML(Str As String) As String
  1469. Return Str.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;").Replace("""", "&quot;")
  1470. End Function
  1471. '正则
  1472. ''' <summary>
  1473. ''' 搜索字符串中的所有正则匹配项。
  1474. ''' </summary>
  1475. Public Function RegexSearch(str As String, regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As List(Of String)
  1476. Try
  1477. RegexSearch = New List(Of String)
  1478. Dim RegexSearchRes = New RegularExpressions.Regex(regex, options).Matches(str)
  1479. If RegexSearchRes Is Nothing Then Return RegexSearch
  1480. For Each item As RegularExpressions.Match In RegexSearchRes
  1481. RegexSearch.Add(item.Value)
  1482. Next
  1483. Catch ex As Exception
  1484. Log(ex, "正则匹配全部项出错")
  1485. Return New List(Of String)
  1486. End Try
  1487. End Function
  1488. ''' <summary>
  1489. ''' 获取字符串中的第一个正则匹配项,若无匹配则返回 Nothing。
  1490. ''' </summary>
  1491. Public Function RegexSeek(str As String, regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As String
  1492. Try
  1493. Dim Result = RegularExpressions.Regex.Match(str, regex, options).Value
  1494. Return If(Result = "", Nothing, Result)
  1495. Catch ex As Exception
  1496. Log(ex, "正则匹配第一项出错")
  1497. Return Nothing
  1498. End Try
  1499. End Function
  1500. ''' <summary>
  1501. ''' 检查字符串是否匹配某正则模式。
  1502. ''' </summary>
  1503. Public Function RegexCheck(str As String, regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As Boolean
  1504. Try
  1505. Return RegularExpressions.Regex.IsMatch(str, regex, options)
  1506. Catch ex As Exception
  1507. Log(ex, "正则检查出错")
  1508. Return False
  1509. End Try
  1510. End Function
  1511. ''' <summary>
  1512. ''' 进行正则替换,会抛出错误。
  1513. ''' </summary>
  1514. Public Function RegexReplace(Input As String, Replacement As String, Regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As String
  1515. Return RegularExpressions.Regex.Replace(Input, Regex, Replacement, options)
  1516. End Function
  1517. #End Region
  1518. #Region "搜索"
  1519. ''' <summary>
  1520. ''' 获取搜索文本的相似度。
  1521. ''' </summary>
  1522. ''' <param name="Source">被搜索的长内容。</param>
  1523. ''' <param name="Query">用户输入的搜索文本。</param>
  1524. Private Function SearchSimilarity(Source As String, Query As String) As Double
  1525. Dim qp As Integer = 0, lenSum As Double = 0
  1526. Source = Source.ToLower.Replace(" ", "")
  1527. Query = Query.ToLower.Replace(" ", "")
  1528. Dim sourceLength As Integer = Source.Length, queryLength As Integer = Query.Length '用于计算最后因数的长度缓存
  1529. Do While qp < Query.Length
  1530. '对 qp 作为开始位置计算
  1531. Dim sp As Integer = 0, lenMax As Integer = 0, spMax As Integer = 0
  1532. '查找以 qp 为头的最大子串
  1533. Do While sp < Source.Length
  1534. '对每个 sp 作为开始位置计算最大子串
  1535. Dim len As Integer = 0
  1536. Do While (qp + len) < Query.Length AndAlso (sp + len) < Source.Length AndAlso Source(sp + len) = Query(qp + len)
  1537. len += 1
  1538. Loop
  1539. '存储 len
  1540. If len > lenMax Then
  1541. lenMax = len
  1542. spMax = sp
  1543. End If
  1544. '根据结果增加 sp
  1545. sp += Math.Max(1, len)
  1546. Loop
  1547. If lenMax > 0 Then
  1548. Source = Source.Substring(0, spMax) & If(Source.Count > spMax + lenMax, Source.Substring(spMax + lenMax), String.Empty) '将源中的对应字段替换空
  1549. '存储 lenSum
  1550. Dim IncWeight = (Math.Pow(1.4, 3 + lenMax) - 3.6) '根据长度加成
  1551. IncWeight *= (1 + 0.3 * Math.Max(0, 3 - Math.Abs(qp - spMax))) '根据位置加成
  1552. lenSum += IncWeight
  1553. End If
  1554. '根据结果增加 qp
  1555. qp += Math.Max(1, lenMax)
  1556. Loop
  1557. '计算结果:重复字段量 × 源长度影响比例
  1558. Return (lenSum / queryLength) * (3 / Math.Pow(sourceLength + 15, 0.5)) * If(queryLength <= 2, 3 - queryLength, 1)
  1559. End Function
  1560. ''' <summary>
  1561. ''' 获取多段文本加权后的相似度。
  1562. ''' </summary>
  1563. Private Function SearchSimilarityWeighted(Source As List(Of KeyValuePair(Of String, Double)), Query As String) As Double
  1564. Dim TotalWeight As Double = 0
  1565. Dim Sum As Double = 0
  1566. For Each Pair In Source
  1567. Sum += SearchSimilarity(Pair.Key, Query) * Pair.Value
  1568. TotalWeight += Pair.Value
  1569. Next
  1570. Return Sum / TotalWeight
  1571. End Function
  1572. ''' <summary>
  1573. ''' 用于搜索的项目。
  1574. ''' </summary>
  1575. Public Class SearchEntry(Of T)
  1576. ''' <summary>
  1577. ''' 该项目对应的源数据。
  1578. ''' </summary>
  1579. Public Item As T
  1580. ''' <summary>
  1581. ''' 该项目用于搜索的源。
  1582. ''' </summary>
  1583. Public SearchSource As List(Of KeyValuePair(Of String, Double))
  1584. ''' <summary>
  1585. ''' 相似度。
  1586. ''' </summary>
  1587. Public Similarity As Double
  1588. ''' <summary>
  1589. ''' 是否完全匹配。
  1590. ''' </summary>
  1591. Public AbsoluteRight As Boolean
  1592. End Class
  1593. ''' <summary>
  1594. ''' 进行多段文本加权搜索,获取相似度较高的数项结果。
  1595. ''' </summary>
  1596. ''' <param name="MaxBlurCount">返回的最大模糊结果数。</param>
  1597. ''' <param name="MinBlurSimilarity">返回结果要求的最低相似度。</param>
  1598. Public Function Search(Of T)(Entries As List(Of SearchEntry(Of T)), Query As String, Optional MaxBlurCount As Integer = 5, Optional MinBlurSimilarity As Double = 0.1) As List(Of SearchEntry(Of T))
  1599. '初始化
  1600. Dim ResultList As New List(Of SearchEntry(Of T))
  1601. If Entries.Count = 0 Then Return ResultList
  1602. '进行搜索,获取相似信息
  1603. For Each Entry In Entries
  1604. Entry.Similarity = SearchSimilarityWeighted(Entry.SearchSource, Query)
  1605. Entry.AbsoluteRight = False
  1606. For Each Pair In Entry.SearchSource
  1607. If Pair.Key.ToLower.Replace(" ", "").Contains(Query.ToLower.Replace(" ", "")) Then Entry.AbsoluteRight = True
  1608. Next
  1609. Next
  1610. '按照相似度进行排序
  1611. Entries = Sort(Entries, Function(Left As SearchEntry(Of T), Right As SearchEntry(Of T)) As Boolean
  1612. If Left.AbsoluteRight Xor Right.AbsoluteRight Then
  1613. Return Left.AbsoluteRight
  1614. Else
  1615. Return Left.Similarity > Right.Similarity
  1616. End If
  1617. End Function)
  1618. '返回结果
  1619. Dim BlurCount As Integer = 0
  1620. For Each Entry In Entries
  1621. If Entry.AbsoluteRight Then
  1622. ResultList.Add(Entry) '完全匹配,直接加入
  1623. Else
  1624. If Entry.Similarity < MinBlurSimilarity OrElse BlurCount = MaxBlurCount Then Exit For '模糊结果边界条件
  1625. ResultList.Add(Entry)
  1626. BlurCount += 1 '模糊结果计数
  1627. End If
  1628. Next
  1629. Return ResultList
  1630. End Function
  1631. #End Region
  1632. #Region "系统"
  1633. ''' <summary>
  1634. ''' 当前程序是否拥有管理员权限。
  1635. ''' </summary>
  1636. Public Function IsAdmin() As Boolean
  1637. Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
  1638. Dim principal As New WindowsPrincipal(id)
  1639. Return principal.IsInRole(WindowsBuiltInRole.Administrator)
  1640. End Function
  1641. ''' <summary>
  1642. ''' 以管理员权限重新运行当前程序。返回是否成功。
  1643. ''' </summary>
  1644. Public Function RerunAsAdmin(Argument As String) As Boolean
  1645. Try
  1646. Process.Start(New ProcessStartInfo(PathWithName) With {.Verb = "runas", .Arguments = Argument})
  1647. Return True
  1648. Catch ex As Exception
  1649. Log(ex, "以管理员权限运行程序失败")
  1650. Return False
  1651. End Try
  1652. End Function
  1653. Private Uuid As Integer = 1
  1654. Private UuidLock As Object
  1655. ''' <summary>
  1656. ''' 获取一个全程序内不会重复的数字(伪 Uuid)。
  1657. ''' </summary>
  1658. Public Function GetUuid() As Integer
  1659. If UuidLock Is Nothing Then UuidLock = New Object
  1660. SyncLock UuidLock
  1661. Uuid += 1
  1662. Return Uuid
  1663. End SyncLock
  1664. End Function
  1665. ''' <summary>
  1666. ''' 将元素与 List 的混合体拆分为元素组。
  1667. ''' </summary>
  1668. Public Function GetFullList(Of T)(data As IList) As List(Of T)
  1669. GetFullList = New List(Of T)
  1670. For i = 0 To data.Count - 1
  1671. If TypeOf data(i) Is ICollection Then
  1672. GetFullList.AddRange(data(i))
  1673. Else
  1674. GetFullList.Add(data(i))
  1675. End If
  1676. Next i
  1677. End Function
  1678. ''' <summary>
  1679. ''' 数组去重。
  1680. ''' </summary>
  1681. Public Function ArrayNoDouble(Of T)(Arr As T(), Optional IsEqual As CompareThreadStart = Nothing) As T()
  1682. Dim ResultArray As New List(Of T)
  1683. For i = 0 To UBound(Arr)
  1684. For ii = i + 1 To UBound(Arr)
  1685. If IsEqual Is Nothing Then
  1686. If Arr(i).Equals(Arr(ii)) Then GoTo NextElement
  1687. Else
  1688. If IsEqual(Arr(i), Arr(ii)) Then GoTo NextElement
  1689. End If
  1690. Next
  1691. ResultArray.Add(Arr(i))
  1692. NextElement:
  1693. Next i
  1694. Return ResultArray.ToArray
  1695. End Function
  1696. ''' <summary>
  1697. ''' 数组去重。
  1698. ''' </summary>
  1699. Public Function ArrayNoDouble(Of T)(Arr As List(Of T), Optional IsEqual As CompareThreadStart = Nothing) As List(Of T)
  1700. Dim ResultArray As New List(Of T)
  1701. For i = 0 To Arr.Count - 1
  1702. For ii = i + 1 To Arr.Count - 1
  1703. If IsEqual Is Nothing Then
  1704. If Arr(i).Equals(Arr(ii)) Then GoTo NextElement
  1705. Else
  1706. If IsEqual(Arr(i), Arr(ii)) Then GoTo NextElement
  1707. End If
  1708. Next
  1709. ResultArray.Add(Arr(i))
  1710. NextElement:
  1711. Next i
  1712. Return ResultArray
  1713. End Function
  1714. ''' <summary>
  1715. ''' 若 Key 不存在于辞典,则加入辞典。
  1716. ''' 若 Key 已存在于辞典,则更新 Value。
  1717. ''' </summary>
  1718. Public Sub DictionaryAdd(Of TKey, TValue)(ByRef Dict As Dictionary(Of TKey, TValue), Key As TKey, Value As TValue)
  1719. If Dict.ContainsKey(Key) Then
  1720. Dict(Key) = Value
  1721. Else
  1722. Dict.Add(Key, Value)
  1723. End If
  1724. End Sub
  1725. ''' <summary>
  1726. ''' 获取格式类似于“11:08:52.037”的当前时间的字符串。
  1727. ''' </summary>
  1728. Public Function GetTimeNow() As String
  1729. Return Date.Now.ToString("HH:mm:ss.fff")
  1730. End Function
  1731. ''' <summary>
  1732. ''' 获取系统运行时间(毫秒),保证为正 Long 且大于 1,但可能突变减小。
  1733. ''' </summary>
  1734. Public Function GetTimeTick() As Long
  1735. Return My.Computer.Clock.TickCount + 2147483651L
  1736. End Function
  1737. ''' <summary>
  1738. ''' 将时间间隔转换为类似“5 分 10 秒前”的易于阅读的形式。
  1739. ''' </summary>
  1740. Public Function GetTimeSpanString(Span As TimeSpan) As String
  1741. Dim EndFix = If(Span.TotalMilliseconds > 0, "后", "前")
  1742. If Span.TotalMilliseconds < 0 Then Span = -Span
  1743. Dim TotalMonthes = Math.Floor(Span.Days / 30)
  1744. If TotalMonthes >= 61 Then
  1745. '5+ 年,“5 年”
  1746. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  1747. ElseIf TotalMonthes >= 12 Then
  1748. '12~60 月,“1 年 2 个月”
  1749. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年" & If((TotalMonthes Mod 12) > 0, " " & (TotalMonthes Mod 12) & " 个月", "")
  1750. ElseIf TotalMonthes >= 4 Then
  1751. '4~11 月,“5 月”
  1752. GetTimeSpanString = TotalMonthes & " 月"
  1753. ElseIf TotalMonthes >= 1 Then
  1754. '1~4 月,“2 月 13 天”
  1755. GetTimeSpanString = TotalMonthes & " 月" & If((Span.Days Mod 30) > 0, " " & (Span.Days Mod 30) & " 天", "")
  1756. ElseIf Span.TotalDays >= 4 Then
  1757. '4~30 天,“23 天”
  1758. GetTimeSpanString = Span.Days & " 天"
  1759. ElseIf Span.TotalDays >= 1 Then
  1760. '1~3 天,“2 天 20 小时”
  1761. GetTimeSpanString = Span.Days & " 天" & If(Span.Hours > 0, " " & Span.Hours & " 小时", "")
  1762. ElseIf Span.TotalHours >= 10 Then
  1763. '10 小时 ~ 1 天,“15 小时”
  1764. GetTimeSpanString = Span.Hours & " 小时"
  1765. ElseIf Span.TotalHours >= 1 Then
  1766. '1~10 小时,“1 小时 20 分钟”
  1767. GetTimeSpanString = Span.Hours & " 小时" & If(Span.Minutes > 0, " " & Span.Minutes & " 分钟", "")
  1768. ElseIf Span.TotalMinutes >= 10 Then
  1769. '10 分钟 ~ 1 小时,“49 分钟”
  1770. GetTimeSpanString = Span.Minutes & " 分钟"
  1771. ElseIf Span.TotalMinutes >= 1 Then
  1772. '1~10 分钟,“9 分 23 秒”
  1773. GetTimeSpanString = Span.Minutes & " 分" & If(Span.Seconds > 0, " " & Span.Seconds & " 秒", "")
  1774. ElseIf Span.TotalSeconds >= 1 Then
  1775. '1 秒 ~ 1 分钟,“23 秒”
  1776. GetTimeSpanString = Span.Seconds & " 秒"
  1777. Else
  1778. '不到 1 秒
  1779. GetTimeSpanString = "1 秒"
  1780. End If
  1781. GetTimeSpanString += EndFix
  1782. End Function
  1783. ''' <summary>
  1784. ''' 获取十进制 Unix 时间戳。
  1785. ''' </summary>
  1786. Public Function GetUnixTimestamp() As Long
  1787. Return (Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000
  1788. End Function
  1789. ''' <summary>
  1790. ''' 用于储存 RaiseByMouse 的 EventArgs。
  1791. ''' </summary>
  1792. Public NotInheritable Class RouteEventArgs
  1793. Inherits EventArgs
  1794. Public RaiseByMouse As Boolean
  1795. Public Handled As Boolean = False
  1796. Public Sub New(Optional RaiseByMouse As Boolean = False)
  1797. Me.RaiseByMouse = RaiseByMouse
  1798. End Sub
  1799. End Class
  1800. ''' <summary>
  1801. ''' 前台运行文件。
  1802. ''' </summary>
  1803. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1804. ''' <param name="Arguments">运行参数。</param>
  1805. Public Sub ShellOnly(FileName As String, Optional Arguments As String = "")
  1806. Using Program As New Process
  1807. Program.StartInfo.Arguments = Arguments
  1808. Program.StartInfo.FileName = FileName
  1809. Log("[System] 执行外部命令:" & FileName & " " & Arguments)
  1810. Program.Start()
  1811. End Using
  1812. End Sub
  1813. ''' <summary>
  1814. ''' 前台运行文件并返回返回值。
  1815. ''' </summary>
  1816. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1817. ''' <param name="Arguments">运行参数。</param>
  1818. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会返回 Result.Timeout。</param>
  1819. Public Function ShellAndGetExitCode(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000) As Result
  1820. Try
  1821. Using Program As New Process
  1822. Program.StartInfo.Arguments = Arguments
  1823. Program.StartInfo.FileName = FileName
  1824. Log("[System] 执行外部命令并等待返回码:" & FileName & " " & Arguments)
  1825. Program.Start()
  1826. If Program.WaitForExit(Timeout) Then
  1827. Return Program.ExitCode
  1828. Else
  1829. Return Result.Timeout
  1830. End If
  1831. End Using
  1832. Catch ex As Exception
  1833. Log(ex, "执行命令失败:" & FileName, LogLevel.Msgbox)
  1834. Return Result.Fail
  1835. End Try
  1836. End Function
  1837. ''' <summary>
  1838. ''' 静默运行文件并返回输出流字符串。执行失败会抛出异常。
  1839. ''' </summary>
  1840. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1841. ''' <param name="Arguments">运行参数。</param>
  1842. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会抛出错误。</param>
  1843. Public Function ShellAndGetOutput(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000, Optional WorkingDirectory As String = Nothing) As String
  1844. Dim Info = New ProcessStartInfo With {
  1845. .Arguments = Arguments,
  1846. .FileName = FileName,
  1847. .UseShellExecute = False,
  1848. .CreateNoWindow = True,
  1849. .RedirectStandardError = True,
  1850. .RedirectStandardOutput = True,
  1851. .WorkingDirectory = If(WorkingDirectory, Path.TrimEnd("\"c))
  1852. }
  1853. If WorkingDirectory IsNot Nothing Then
  1854. If Info.EnvironmentVariables.ContainsKey("appdata") Then
  1855. Info.EnvironmentVariables("appdata") = WorkingDirectory
  1856. Else
  1857. Info.EnvironmentVariables.Add("appdata", WorkingDirectory)
  1858. End If
  1859. End If
  1860. Log("[System] 执行外部命令并等待返回结果:" & FileName & " " & Arguments)
  1861. Using Program As New Process() With {.StartInfo = Info}
  1862. Program.Start()
  1863. Program.WaitForExit(Timeout)
  1864. If Not Program.HasExited Then Program.Kill()
  1865. Return Program.StandardOutput.ReadToEnd & Program.StandardError.ReadToEnd
  1866. End Using
  1867. End Function
  1868. ''' <summary>
  1869. ''' 在新的工作线程中执行代码。
  1870. ''' </summary>
  1871. Public Function RunInNewThread(Action As Action, Name As String, Optional Priority As ThreadPriority = ThreadPriority.Normal) As Thread
  1872. Dim th As New Thread(Sub()
  1873. Try
  1874. Action()
  1875. Catch ex As ThreadInterruptedException
  1876. Log(Name & ":线程已中止")
  1877. Catch ex As Exception
  1878. Log(ex, Name & ":线程执行失败", LogLevel.Feedback)
  1879. End Try
  1880. End Sub) With {.Name = Name, .Priority = Priority}
  1881. th.Start()
  1882. Return th
  1883. End Function
  1884. ''' <summary>
  1885. ''' 确保在 UI 线程中执行代码。
  1886. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  1887. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  1888. ''' </summary>
  1889. Public Function RunInUiWait(Of Output)(Action As Func(Of Output)) As Output
  1890. If RunInUi() Then
  1891. Return Action()
  1892. Else
  1893. Return Application.Current.Dispatcher.Invoke(Action)
  1894. End If
  1895. End Function
  1896. ''' <summary>
  1897. ''' 确保在 UI 线程中执行代码。
  1898. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  1899. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  1900. ''' </summary>
  1901. Public Sub RunInUiWait(Action As Action)
  1902. If RunInUi() Then
  1903. Action()
  1904. Else
  1905. Application.Current.Dispatcher.Invoke(Action)
  1906. End If
  1907. End Sub
  1908. ''' <summary>
  1909. ''' 确保在 UI 线程中执行代码,代码按触发顺序执行。
  1910. ''' 如果当前并非 UI 线程,也不阻断当前线程的执行。
  1911. ''' </summary>
  1912. Public Sub RunInUi(Action As Action, Optional ForceWaitUntilLoaded As Boolean = False)
  1913. If ForceWaitUntilLoaded Then
  1914. Application.Current.Dispatcher.InvokeAsync(Action, Threading.DispatcherPriority.Loaded)
  1915. ElseIf RunInUi() Then
  1916. Action()
  1917. Else
  1918. Application.Current.Dispatcher.InvokeAsync(Action)
  1919. End If
  1920. End Sub
  1921. ''' <summary>
  1922. ''' 确保在工作线程中执行代码。
  1923. ''' </summary>
  1924. Public Sub RunInThread(Action As Action)
  1925. If RunInUi() Then
  1926. RunInNewThread(Action, "Runtime Invoke " & GetUuid() & "#")
  1927. Else
  1928. Action()
  1929. End If
  1930. End Sub
  1931. ''' <summary>
  1932. ''' 按照既定的函数进行选择排序。
  1933. ''' </summary>
  1934. ''' <param name="SortRule">传入两个对象,若第一个对象应该排在前面,则返回 True。</param>
  1935. Public Function Sort(Of T)(List As IList(Of T), SortRule As CompareThreadStart) As List(Of T)
  1936. Dim NewList As New List(Of T)
  1937. While List.Count > 0
  1938. Dim Highest = List(0)
  1939. For i = 1 To List.Count - 1
  1940. If SortRule(List(i), Highest) Then Highest = List(i)
  1941. Next
  1942. List.Remove(Highest)
  1943. NewList.Add(Highest)
  1944. End While
  1945. Return NewList
  1946. End Function
  1947. Public Delegate Function CompareThreadStart(Left, Right) As Boolean
  1948. ''' <summary>
  1949. ''' 获取程序启动参数。
  1950. ''' </summary>
  1951. ''' <param name="Name">参数名。</param>
  1952. ''' <param name="DefaultValue">默认值。</param>
  1953. Public Function GetProgramArgument(Name As String, Optional DefaultValue As Object = "")
  1954. Dim AllArguments() As String = Command.Split(" ")
  1955. For i = 0 To AllArguments.Length - 1
  1956. If AllArguments(i) = "-" & Name Then
  1957. If AllArguments.Length = i + 1 OrElse AllArguments(i + 1).StartsWith("-") Then Return True
  1958. Return AllArguments(i + 1)
  1959. End If
  1960. Next
  1961. Return DefaultValue
  1962. End Function
  1963. ''' <summary>
  1964. ''' 时间戳转化为日期。
  1965. ''' </summary>
  1966. Public Function GetDate(timeStamp As Integer) As Date
  1967. Dim dtStart As Date = TimeZone.CurrentTimeZone.ToLocalTime(New Date(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
  1968. Dim lTime As Long = (CLng(timeStamp) * 10000000)
  1969. Return dtStart.Add(New TimeSpan(lTime))
  1970. End Function
  1971. ''' <summary>
  1972. ''' 将 UTC 时间转化为当前时区的时间。
  1973. ''' </summary>
  1974. Public Function GetLocalTime(UtcDate As Date) As Date
  1975. Return DateTime.SpecifyKind(UtcDate, DateTimeKind.Utc).ToLocalTime
  1976. End Function
  1977. ''' <summary>
  1978. ''' 打开网页。
  1979. ''' </summary>
  1980. Public Sub OpenWebsite(Url As String)
  1981. Try
  1982. Log("[System] 正在打开网页:" & Url)
  1983. Process.Start(Url)
  1984. Catch ex As Exception
  1985. Log(ex, "无法打开网页(" & Url & ")")
  1986. ClipboardSet(Url, False)
  1987. MyMsgBox("可能由于浏览器未正确配置,PCL2 无法为你打开网页。" & vbCrLf & "网址已经复制到剪贴板,若有需要可以手动粘贴访问。", "无法打开网页")
  1988. End Try
  1989. End Sub
  1990. ''' <summary>
  1991. ''' 打开 explorer。注意参数中的路径要尽量加上双引号!
  1992. ''' </summary>
  1993. Public Sub OpenExplorer(Argument As String)
  1994. Try
  1995. ShellOnly("explorer.exe", Argument)
  1996. Catch ex As Exception
  1997. Log(ex, "打开资源管理器失败,请尝试关闭安全软件(如 360 安全卫士)", LogLevel.Msgbox)
  1998. End Try
  1999. End Sub
  2000. ''' <summary>
  2001. ''' 设置剪贴板。将在另一线程运行,且不会抛出异常。
  2002. ''' </summary>
  2003. Public Sub ClipboardSet(Text As String, Optional ShowSuccessHint As Boolean = True)
  2004. RunInThread(Sub()
  2005. Dim RetryCount As Integer = 0
  2006. Retry:
  2007. Try
  2008. RunInUi(Sub()
  2009. My.Computer.Clipboard.Clear()
  2010. My.Computer.Clipboard.SetText(Text)
  2011. End Sub)
  2012. Catch ex As Exception
  2013. RetryCount += 1
  2014. If RetryCount <= 5 Then
  2015. Thread.Sleep(20)
  2016. GoTo Retry
  2017. Else
  2018. Log(ex, "可能由于剪贴板被其他程序占用,文本复制失败", LogLevel.Hint)
  2019. End If
  2020. End Try
  2021. If ShowSuccessHint Then Hint("已成功复制!", HintType.Finish)
  2022. End Sub)
  2023. End Sub
  2024. ''' <summary>
  2025. ''' 以 Byte() 形式获取程序中的资源。
  2026. ''' </summary>
  2027. Public Function GetResources(ResourceName As String) As Byte()
  2028. Log("[System] 获取资源:" & ResourceName)
  2029. Dim Raw As Byte() = My.Resources.ResourceManager.GetObject(ResourceName)
  2030. Return Raw
  2031. End Function
  2032. #End Region
  2033. #Region "UI"
  2034. '边距改变
  2035. ''' <summary>
  2036. ''' 相对增减控件的左边距。
  2037. ''' </summary>
  2038. Public Sub DeltaLeft(control As FrameworkElement, newValue As Double)
  2039. '安全性检查
  2040. DebugAssert(Not Double.IsNaN(newValue))
  2041. DebugAssert(Not Double.IsInfinity(newValue))
  2042. If TypeOf control Is Window Then
  2043. '窗口改变
  2044. CType(control, Window).Left += newValue
  2045. Else
  2046. '根据 HorizontalAlignment 改变数值
  2047. Select Case control.HorizontalAlignment
  2048. Case HorizontalAlignment.Left, HorizontalAlignment.Stretch
  2049. control.Margin = New Thickness(control.Margin.Left + newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2050. Case HorizontalAlignment.Right
  2051. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right - newValue, control.Margin.Bottom)
  2052. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2053. Case Else
  2054. DebugAssert(False)
  2055. End Select
  2056. End If
  2057. End Sub
  2058. ''' <summary>
  2059. ''' 设置控件的左边距。(仅针对置左控件)
  2060. ''' </summary>
  2061. Public Sub SetLeft(control As FrameworkElement, newValue As Double)
  2062. DebugAssert(control.HorizontalAlignment = HorizontalAlignment.Left)
  2063. control.Margin = New Thickness(newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2064. End Sub
  2065. ''' <summary>
  2066. ''' 相对增减控件的上边距。
  2067. ''' </summary>
  2068. Public Sub DeltaTop(control As FrameworkElement, newValue As Double)
  2069. '安全性检查
  2070. DebugAssert(Not Double.IsNaN(newValue))
  2071. DebugAssert(Not Double.IsInfinity(newValue))
  2072. If TypeOf control Is Window Then
  2073. '窗口改变
  2074. CType(control, Window).Top += newValue
  2075. Else
  2076. '根据 VerticalAlignment 改变数值
  2077. Select Case control.VerticalAlignment
  2078. Case VerticalAlignment.Top
  2079. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top + newValue, control.Margin.Right, control.Margin.Bottom)
  2080. Case VerticalAlignment.Bottom
  2081. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, control.Margin.Bottom - newValue)
  2082. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2083. Case Else
  2084. DebugAssert(False)
  2085. End Select
  2086. End If
  2087. 'If Double.IsNaN(newValue) OrElse Double.IsInfinity(newValue) Then Exit Sub '安全性检查
  2088. 'Select Case control.VerticalAlignment
  2089. ' Case VerticalAlignment.Top, VerticalAlignment.Stretch, VerticalAlignment.Center
  2090. ' control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2091. ' Case VerticalAlignment.Bottom
  2092. ' control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, -newValue)
  2093. ' 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, CType(control.Parent, Object).ActualHeight - control.ActualHeight - newValue)
  2094. 'End Select
  2095. End Sub
  2096. ''' <summary>
  2097. ''' 设置控件的顶边距。(仅针对置上控件)
  2098. ''' </summary>
  2099. Public Sub SetTop(control As FrameworkElement, newValue As Double)
  2100. DebugAssert(control.VerticalAlignment = VerticalAlignment.Top)
  2101. control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2102. End Sub
  2103. 'DPI 转换
  2104. Public ReadOnly DPI As Integer = System.Drawing.Graphics.FromHwnd(IntPtr.Zero).DpiX
  2105. ''' <summary>
  2106. ''' 将经过 DPI 缩放的 WPF 尺寸转化为实际的像素尺寸。
  2107. ''' </summary>
  2108. Public Function GetPixelSize(WPFSize As Double) As Double
  2109. Return WPFSize / 96 * DPI
  2110. End Function
  2111. ''' <summary>
  2112. ''' 将实际的像素尺寸转化为经过 DPI 缩放的 WPF 尺寸。
  2113. ''' </summary>
  2114. Public Function GetWPFSize(PixelSize As Double) As Double
  2115. Return PixelSize * 96 / DPI
  2116. End Function
  2117. 'UI 截图
  2118. ''' <summary>
  2119. ''' 将某个控件的呈现转换为图片。
  2120. ''' </summary>
  2121. Public Function ControlBrush(UI As FrameworkElement) As ImageBrush
  2122. Dim Width = UI.ActualWidth, Height = UI.ActualHeight
  2123. If Width < 1 OrElse Height < 1 Then Return New ImageBrush
  2124. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Pbgra32)
  2125. bmp.Render(UI)
  2126. Return New ImageBrush(bmp)
  2127. End Function
  2128. ''' <summary>
  2129. ''' 将某个控件的模拟呈现转换为图片。
  2130. ''' </summary>
  2131. Public Function ControlBrush(UI As FrameworkElement, Width As Double, Height As Double, Optional Left As Double = 0, Optional Top As Double = 0) As ImageBrush
  2132. UI.Measure(New Size(Width, Height))
  2133. UI.Arrange(New Rect(0, 0, Width, Height))
  2134. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Default)
  2135. bmp.Render(UI)
  2136. If Not (Left = 0 AndAlso Top = 0) Then UI.Arrange(New Rect(Left, Top, Width, Height))
  2137. Return New ImageBrush(bmp)
  2138. End Function
  2139. ''' <summary>
  2140. ''' 将 UI 内容固定为图片并进行 Clear。
  2141. ''' </summary>
  2142. Public Sub ControlFreeze(UI As Panel)
  2143. UI.Background = ControlBrush(UI)
  2144. UI.Children.Clear()
  2145. End Sub
  2146. ''' <summary>
  2147. ''' 将 UI 内容固定为图片并进行 Clear。
  2148. ''' </summary>
  2149. Public Sub ControlFreeze(UI As Border)
  2150. UI.Background = ControlBrush(UI)
  2151. UI.Child = Nothing
  2152. End Sub
  2153. ''' <summary>
  2154. ''' 将 XML 转换为对应 UI 对象。
  2155. ''' </summary>
  2156. Public Function GetObjectFromXML(Str As XElement)
  2157. Return GetObjectFromXML(Str.ToString)
  2158. End Function
  2159. ''' <summary>
  2160. ''' 将 XML 转换为对应 UI 对象。
  2161. ''' </summary>
  2162. Public Function GetObjectFromXML(Str As String)
  2163. Using Stream As New MemoryStream
  2164. Using Writer As New StreamWriter(Stream)
  2165. Writer.Write(Str)
  2166. Writer.Flush()
  2167. Stream.Position = 0
  2168. Return XamlReader.Load(Stream)
  2169. End Using
  2170. End Using
  2171. End Function
  2172. Private ReadOnly UiThreadId As Integer = Thread.CurrentThread.ManagedThreadId
  2173. ''' <summary>
  2174. ''' 当前线程是否为主线程。
  2175. ''' </summary>
  2176. Public Function RunInUi() As Boolean
  2177. Return Thread.CurrentThread.ManagedThreadId = UiThreadId
  2178. End Function
  2179. #End Region
  2180. #Region "Debug"
  2181. Public ModeDebug As Boolean = False
  2182. 'Log
  2183. Public Enum LogLevel
  2184. ''' <summary>
  2185. ''' 不提示,只记录日志。
  2186. ''' </summary>
  2187. Normal = 0
  2188. ''' <summary>
  2189. ''' 只提示开发者。
  2190. ''' </summary>
  2191. Developer = 1
  2192. ''' <summary>
  2193. ''' 只提示开发者与调试模式用户。
  2194. ''' </summary>
  2195. Debug = 2
  2196. ''' <summary>
  2197. ''' 弹出提示所有用户。
  2198. ''' </summary>
  2199. Hint = 3
  2200. ''' <summary>
  2201. ''' 弹窗,不要求反馈。
  2202. ''' </summary>
  2203. Msgbox = 4
  2204. ''' <summary>
  2205. ''' 弹窗,要求反馈。
  2206. ''' </summary>
  2207. Feedback = 5
  2208. ''' <summary>
  2209. ''' 弹窗,结束程序。
  2210. ''' </summary>
  2211. Assert = 6
  2212. End Enum
  2213. Private LogList As New StringBuilder
  2214. Private LogWritter As StreamWriter
  2215. Public Sub LogStart()
  2216. RunInNewThread(Sub()
  2217. Dim IsInitSuccess As Boolean = True
  2218. Try
  2219. For i = 4 To 1 Step -1
  2220. If File.Exists(Path & "PCL\Log" & i & ".txt") Then
  2221. If File.Exists(Path & "PCL\Log" & (i + 1) & ".txt") Then File.Delete(Path & "PCL\Log" & (i + 1) & ".txt")
  2222. CopyFile(Path & "PCL\Log" & i & ".txt", Path & "PCL\Log" & (i + 1) & ".txt")
  2223. End If
  2224. Next
  2225. File.Create(Path & "PCL\Log1.txt").Dispose()
  2226. Catch ex As IOException
  2227. IsInitSuccess = False
  2228. Hint("可能同时开启了多个 PCL2,程序可能会出现未知问题!", HintType.Critical)
  2229. Log(ex, "日志初始化失败(疑似文件占用问题)")
  2230. Catch ex As Exception
  2231. IsInitSuccess = False
  2232. Log(ex, "日志初始化失败", LogLevel.Hint)
  2233. End Try
  2234. Try
  2235. LogWritter = New StreamWriter(Path & "PCL\Log1.txt", True) With {.AutoFlush = True}
  2236. Catch ex As Exception
  2237. LogWritter = Nothing
  2238. Log(ex, "日志写入失败", LogLevel.Hint)
  2239. End Try
  2240. While True
  2241. If IsInitSuccess Then
  2242. LogFlush()
  2243. Else
  2244. LogList = New StringBuilder '清空 LogList 避免内存爆炸
  2245. End If
  2246. Thread.Sleep(50)
  2247. End While
  2248. End Sub, "Log Writer", ThreadPriority.Lowest)
  2249. End Sub
  2250. Private ReadOnly LogFlushLock As New Object '防止外部调用 LogFlush 时同时输出多次日志
  2251. Public Sub LogFlush()
  2252. On Error Resume Next
  2253. If LogWritter Is Nothing Then Exit Sub
  2254. Dim Log As String = Nothing
  2255. SyncLock LogFlushLock
  2256. If LogList.Length > 0 Then
  2257. Dim LogListCache As StringBuilder
  2258. LogListCache = LogList
  2259. LogList = New StringBuilder
  2260. Log = LogListCache.ToString
  2261. End If
  2262. End SyncLock
  2263. If Log IsNot Nothing Then
  2264. LogWritter.Write(Log)
  2265. End If
  2266. End Sub
  2267. Private ReadOnly LogListLock As New Object '防止日志乱码,只在调试模式下启用
  2268. ''' <summary>
  2269. ''' 输出 Log。
  2270. ''' </summary>
  2271. ''' <param name="Title">如果要求弹窗,指定弹窗的标题。</param>
  2272. Public Sub Log(Text As String, Optional Level As LogLevel = LogLevel.Normal, Optional Title As String = "出现错误")
  2273. On Error Resume Next
  2274. '放在最后会导致无法显示极端错误下的弹窗(如无法写入日志文件)
  2275. '处理错误会导致再次调用 Log() 导致无限循环
  2276. '输出日志
  2277. Dim AppendText As String = "[" & GetTimeNow() & "] " & Text & vbCrLf '减轻同步锁占用
  2278. If ModeDebug Then
  2279. SyncLock LogListLock
  2280. LogList.Append(AppendText)
  2281. End SyncLock
  2282. Else
  2283. LogList.Append(AppendText)
  2284. End If
  2285. #If DEBUG Then
  2286. Console.Write(AppendText)
  2287. #End If
  2288. If IsProgramEnded OrElse Level = LogLevel.Normal Then Exit Sub
  2289. '去除前缀
  2290. Text = RegexReplace(Text, "", "\[[^\]]+?\] ")
  2291. '输出提示
  2292. Select Case Level
  2293. #If DEBUG Then
  2294. Case LogLevel.Developer
  2295. Hint("[开发者模式] " & Text, HintType.Info, False)
  2296. Case LogLevel.Debug
  2297. Hint("[调试模式] " & Text, HintType.Info, False)
  2298. #Else
  2299. Case LogLevel.Developer
  2300. Case LogLevel.Debug
  2301. If ModeDebug Then Hint("[调试模式] " & Text, HintType.Info, False)
  2302. #End If
  2303. Case LogLevel.Hint
  2304. Hint(Text, HintType.Critical, False)
  2305. Case LogLevel.Msgbox
  2306. MyMsgBox(Text, Title, IsWarn:=True)
  2307. Case LogLevel.Feedback
  2308. If CanFeedback(False) Then
  2309. If MyMsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  2310. Else
  2311. MyMsgBox(Text & vbCrLf & vbCrLf & "将 PCL2 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  2312. End If
  2313. Case LogLevel.Assert
  2314. Dim Time As Long = GetTimeTick()
  2315. If CanFeedback(False) Then
  2316. If MsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  2317. Else
  2318. MsgBox(Text & vbCrLf & vbCrLf & "将 PCL2 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  2319. End If
  2320. If GetTimeTick() - Time < 1500 Then
  2321. '弹窗无法保留
  2322. Log("[System] PCL 已崩溃:" & vbCrLf & Text)
  2323. FormMain.EndProgramForce(Result.Exception)
  2324. Else
  2325. FormMain.EndProgramForce(Result.Fail)
  2326. End If
  2327. End Select
  2328. End Sub
  2329. ''' <summary>
  2330. ''' 输出错误信息。
  2331. ''' </summary>
  2332. ''' <param name="Desc">错误描述。会在处理时在末尾加入冒号。</param>
  2333. Public Sub Log(Ex As Exception, Desc As String, Optional Level As LogLevel = LogLevel.Debug, Optional Title As String = "出现错误")
  2334. On Error Resume Next
  2335. If TypeOf Ex Is ThreadInterruptedException Then Exit Sub
  2336. '获取错误信息
  2337. Dim ExFull As String = Desc & ":" & GetExceptionDetail(Ex)
  2338. '输出日志
  2339. Dim AppendText As String = "[" & GetTimeNow() & "] " & Desc & ":" & GetExceptionDetail(Ex, True) & vbCrLf '减轻同步锁占用
  2340. If ModeDebug Then
  2341. SyncLock LogListLock
  2342. LogList.Append(AppendText)
  2343. End SyncLock
  2344. Else
  2345. LogList.Append(AppendText)
  2346. End If
  2347. #If DEBUG Then
  2348. Console.Write(AppendText)
  2349. #End If
  2350. If IsProgramEnded Then Exit Sub
  2351. '输出提示
  2352. Select Case Level
  2353. Case LogLevel.Normal
  2354. #If DEBUG Then
  2355. Case LogLevel.Developer
  2356. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2357. Hint("[开发者模式] " & ExLine, HintType.Info, False)
  2358. Case LogLevel.Debug
  2359. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2360. Hint("[调试模式] " & ExLine, HintType.Info, False)
  2361. #Else
  2362. Case LogLevel.Developer
  2363. Case LogLevel.Debug
  2364. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2365. If ModeDebug Then Hint("[调试模式] " & ExLine, HintType.Info, False)
  2366. #End If
  2367. Case LogLevel.Hint
  2368. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2369. Hint(ExLine, HintType.Critical, False)
  2370. Case LogLevel.Msgbox
  2371. MyMsgBox(ExFull, Title, IsWarn:=True)
  2372. Case LogLevel.Feedback
  2373. If CanFeedback(False) Then
  2374. If MyMsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  2375. Else
  2376. MyMsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL2 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  2377. End If
  2378. Case LogLevel.Assert
  2379. Dim Time As Long = GetTimeTick()
  2380. If CanFeedback(False) Then
  2381. If MsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  2382. Else
  2383. MsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL2 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  2384. End If
  2385. If GetTimeTick() - Time < 1500 Then
  2386. '弹窗无法保留
  2387. Log("[System] PCL 已崩溃:" & vbCrLf & ExFull)
  2388. FormMain.EndProgramForce(Result.Exception)
  2389. Else
  2390. FormMain.EndProgramForce(Result.Fail)
  2391. End If
  2392. End Select
  2393. End Sub
  2394. '反馈
  2395. Public Sub Feedback(Optional ShowMsgbox As Boolean = True, Optional ForceOpenLog As Boolean = False)
  2396. On Error Resume Next
  2397. FeedbackInfo()
  2398. If ForceOpenLog OrElse (ShowMsgbox AndAlso MyMsgBox("若你在汇报一个 Bug,请点击 打开文件夹 按钮,并上传 Log(1~5).txt 中包含错误信息的文件。" & vbCrLf & "游戏崩溃一般与启动器无关,请不要因为游戏崩溃而提交反馈。", "反馈提交提醒", "打开文件夹", "不需要") = 1) Then
  2399. OpenExplorer("""" & Path & "PCL\""")
  2400. End If
  2401. OpenWebsite("https://github.com/Hex-Dragon/PCL2/issues/")
  2402. End Sub
  2403. Public Function CanFeedback(ShowHint As Boolean) As Boolean
  2404. If False.Equals(PageSetupSystem.IsLauncherNewest) Then
  2405. If ShowHint Then MyMsgBox("你的 PCL2 不是最新版,因此无法提交反馈。" & vbCrLf & "请先在 设置 → 启动器 中更新启动器,确认该问题在最新版中依然存在,然后再提交反馈。", "无法提交反馈")
  2406. Return False
  2407. Else
  2408. Return True
  2409. End If
  2410. End Function
  2411. ''' <summary>
  2412. ''' 在日志中输出系统诊断信息。
  2413. ''' </summary>
  2414. Public Sub FeedbackInfo()
  2415. On Error Resume Next
  2416. Log("[System] 诊断信息:" & vbCrLf &
  2417. "操作系统:" & My.Computer.Info.OSFullName & vbCrLf &
  2418. "剩余内存:" & Int(My.Computer.Info.AvailablePhysicalMemory / 1024 / 1024) & " M / " & Int(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024) & " M" & vbCrLf &
  2419. "DPI:" & DPI & "(" & Math.Round(DPI / 96, 2) * 100 & "%)" & vbCrLf &
  2420. "MC 文件夹:" & If(PathMcFolder, "Nothing") & vbCrLf &
  2421. "文件位置:" & Path)
  2422. End Sub
  2423. '断言
  2424. Public Sub DebugAssert(Exp As Boolean)
  2425. If Not Exp Then Throw New Exception("断言命中")
  2426. End Sub
  2427. '获取当前的堆栈信息
  2428. Public Function GetStackTrace() As String
  2429. Dim Stack As New StackTrace()
  2430. Return Join(Stack.GetFrames().Skip(1).Select(Function(f) f.GetMethod).
  2431. Select(Function(f) f.Name & "(" & Join(f.GetParameters.Select(Function(p) p.ToString).ToList, ", ") & ") - " & f.Module.ToString).ToList,
  2432. vbCrLf).Replace(vbCrLf & vbCrLf, vbCrLf)
  2433. End Function
  2434. #End Region
  2435. #Region "随机"
  2436. Private ReadOnly Random As New Random
  2437. ''' <summary>
  2438. ''' 随机选择其一。
  2439. ''' </summary>
  2440. Public Function RandomOne(Of T)(objects As ICollection(Of T)) As T
  2441. Return objects(RandomInteger(0, objects.Count - 1))
  2442. End Function
  2443. ''' <summary>
  2444. ''' 取随机整数。
  2445. ''' </summary>
  2446. Public Function RandomInteger(min As Integer, max As Integer) As Integer
  2447. Return Math.Floor((max - min + 1) * Random.NextDouble) + min
  2448. End Function
  2449. ''' <summary>
  2450. ''' 将数组随机打乱。
  2451. ''' </summary>
  2452. Public Function RandomChaos(Of T)(array As IList(Of T)) As IList(Of T)
  2453. RandomChaos = New List(Of T)
  2454. Do While array.Count > 0
  2455. Dim i As Integer = RandomInteger(0, array.Count - 1)
  2456. RandomChaos.Add(array(i))
  2457. array.RemoveAt(i)
  2458. Loop
  2459. End Function
  2460. #End Region
  2461. End Module