ModBase.vb 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571
  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.0" '不含分支前缀的显示用版本名
  11. Public Const VersionStandardCode As String = "2.4.0." & VersionBranchCode '标准格式的四段式版本号
  12. #If BETA Then
  13. Public Const VersionCode As Integer = 265 'Release
  14. #Else
  15. Public Const VersionCode As Integer = 266 '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. ''' 程序的缓存文件夹路径,以“\”结尾。
  79. ''' </summary>
  80. Public PathTemp As String = If(Setup.Get("SystemSystemCache") = "", IO.Path.GetTempPath() & "PCL\", Setup.Get("SystemSystemCache")).ToString.Replace("/", "\").TrimEnd("\") & "\"
  81. ''' <summary>
  82. ''' AppData 中的 PCL 文件夹路径,以“\”结尾。
  83. ''' </summary>
  84. Public PathAppdata As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\PCL\"
  85. #End Region
  86. #Region "矢量图标"
  87. Public Class Logo
  88. ''' <summary>
  89. ''' 图标按钮,心(空心),1.1x
  90. ''' </summary>
  91. 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"
  92. ''' <summary>
  93. ''' 图标按钮,心(实心),1.1x
  94. ''' </summary>
  95. 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"
  96. ''' <summary>
  97. ''' 图标按钮,垃圾桶,1.1x
  98. ''' </summary>
  99. 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"
  100. ''' <summary>
  101. ''' 图标按钮,笔,1x
  102. ''' </summary>
  103. 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"
  104. ''' <summary>
  105. ''' 图标按钮,齿轮,1.1x
  106. ''' </summary>
  107. 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"
  108. ''' <summary>
  109. ''' 图标按钮,重置,0.9x
  110. ''' </summary>
  111. 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"
  112. ''' <summary>
  113. ''' 图标按钮,刷新,0.85x
  114. ''' </summary>
  115. 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"
  116. ''' <summary>
  117. ''' 图标按钮,软盘,1x
  118. ''' </summary>
  119. 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"
  120. ''' <summary>
  121. ''' 图标按钮,信息,1.05x
  122. ''' </summary>
  123. 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"
  124. ''' <summary>
  125. ''' 图标按钮,列表,1x
  126. ''' </summary>
  127. 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"
  128. ''' <summary>
  129. ''' 图标按钮,文件夹,1.15x
  130. ''' </summary>
  131. 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"
  132. ''' <summary>
  133. ''' 图标按钮,名片,1.1x
  134. ''' </summary>
  135. 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"
  136. ''' <summary>
  137. ''' 图标按钮,×,0.85x
  138. ''' </summary>
  139. 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"
  140. ''' <summary>
  141. ''' 图标按钮,Mojang,1.1x
  142. ''' </summary>
  143. 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"
  144. ''' <summary>
  145. ''' 图标按钮,用户,0.95x
  146. ''' </summary>
  147. 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"
  148. ''' <summary>
  149. ''' 图标,音符,1x
  150. ''' </summary>
  151. 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"
  152. ''' <summary>
  153. ''' 图标,播放,0.8x
  154. ''' </summary>
  155. 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"
  156. End Class
  157. #End Region
  158. #Region "自定义类"
  159. ''' <summary>
  160. ''' 支持小数与常见类型隐式转换的颜色。
  161. ''' </summary>
  162. Public Class MyColor
  163. Public A As Double = 255
  164. Public R As Double = 0
  165. Public G As Double = 0
  166. Public B As Double = 0
  167. '类型转换
  168. Public Shared Widening Operator CType(str As String) As MyColor
  169. Return New MyColor(str)
  170. End Operator
  171. Public Shared Widening Operator CType(col As Color) As MyColor
  172. Return New MyColor(col)
  173. End Operator
  174. Public Shared Widening Operator CType(conv As MyColor) As Color
  175. Return Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  176. End Operator
  177. Public Shared Widening Operator CType(conv As MyColor) As System.Drawing.Color
  178. Return System.Drawing.Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  179. End Operator
  180. Public Shared Widening Operator CType(bru As SolidColorBrush) As MyColor
  181. Return New MyColor(bru.Color)
  182. End Operator
  183. Public Shared Widening Operator CType(conv As MyColor) As SolidColorBrush
  184. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  185. End Operator
  186. Public Shared Widening Operator CType(bru As Brush) As MyColor
  187. Return New MyColor(bru)
  188. End Operator
  189. Public Shared Widening Operator CType(conv As MyColor) As Brush
  190. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  191. End Operator
  192. '颜色运算
  193. Public Shared Operator +(a As MyColor, b As MyColor) As MyColor
  194. Return New MyColor With {.A = a.A + b.A, .B = a.B + b.B, .G = a.G + b.G, .R = a.R + b.R}
  195. End Operator
  196. Public Shared Operator -(a As MyColor, b As MyColor) As MyColor
  197. Return New MyColor With {.A = a.A - b.A, .B = a.B - b.B, .G = a.G - b.G, .R = a.R - b.R}
  198. End Operator
  199. Public Shared Operator *(a As MyColor, b As Double) As MyColor
  200. Return New MyColor With {.A = a.A * b, .B = a.B * b, .G = a.G * b, .R = a.R * b}
  201. End Operator
  202. Public Shared Operator /(a As MyColor, b As Double) As MyColor
  203. Return New MyColor With {.A = a.A / b, .B = a.B / b, .G = a.G / b, .R = a.R / b}
  204. End Operator
  205. Public Shared Operator =(a As MyColor, b As MyColor) As Boolean
  206. If IsNothing(a) AndAlso IsNothing(b) Then Return True
  207. If IsNothing(a) OrElse IsNothing(b) Then Return False
  208. Return a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B
  209. End Operator
  210. Public Shared Operator <>(a As MyColor, b As MyColor) As Boolean
  211. If IsNothing(a) AndAlso IsNothing(b) Then Return False
  212. If IsNothing(a) OrElse IsNothing(b) Then Return True
  213. Return Not (a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B)
  214. End Operator
  215. '构造函数
  216. Public Sub New()
  217. End Sub
  218. Public Sub New(col As Color)
  219. Me.A = col.A
  220. Me.R = col.R
  221. Me.G = col.G
  222. Me.B = col.B
  223. End Sub
  224. Public Sub New(HexString As String)
  225. Dim StringColor As Media.Color = ColorConverter.ConvertFromString(HexString)
  226. A = StringColor.A
  227. R = StringColor.R
  228. G = StringColor.G
  229. B = StringColor.B
  230. End Sub
  231. Public Sub New(newA As Double, col As MyColor)
  232. Me.A = newA
  233. Me.R = col.R
  234. Me.G = col.G
  235. Me.B = col.B
  236. End Sub
  237. Public Sub New(newR As Double, newG As Double, newB As Double)
  238. Me.A = 255
  239. Me.R = newR
  240. Me.G = newG
  241. Me.B = newB
  242. End Sub
  243. Public Sub New(newA As Double, newR As Double, newG As Double, newB As Double)
  244. Me.A = newA
  245. Me.R = newR
  246. Me.G = newG
  247. Me.B = newB
  248. End Sub
  249. Public Sub New(brush As Brush)
  250. Dim Color As Color = CType(brush, SolidColorBrush).Color
  251. A = Color.A
  252. R = Color.R
  253. G = Color.G
  254. B = Color.B
  255. End Sub
  256. Public Sub New(brush As SolidColorBrush)
  257. Dim Color As Color = brush.Color
  258. A = Color.A
  259. R = Color.R
  260. G = Color.G
  261. B = Color.B
  262. End Sub
  263. Public Sub New(obj As Object)
  264. If obj Is Nothing Then
  265. A = 255 : R = 255 : G = 255 : B = 255
  266. Else
  267. If TypeOf obj Is SolidColorBrush Then
  268. '避免反复获取 Color 对象造成性能下降
  269. Dim Color As Color = CType(obj, SolidColorBrush).Color
  270. A = Color.A
  271. R = Color.R
  272. G = Color.G
  273. B = Color.B
  274. Else
  275. A = obj.A
  276. R = obj.R
  277. G = obj.G
  278. B = obj.B
  279. End If
  280. End If
  281. End Sub
  282. 'HSL
  283. Public Function Hue(v1 As Double, v2 As Double, vH As Double) As Double
  284. If vH < 0 Then vH += 1
  285. If vH > 1 Then vH -= 1
  286. If vH < 0.16667 Then Return v1 + (v2 - v1) * 6 * vH
  287. If vH < 0.5 Then Return v2
  288. If vH < 0.66667 Then Return v1 + (v2 - v1) * (4 - vH * 6)
  289. Return v1
  290. End Function
  291. Public Function FromHSL(sH As Double, sS As Double, sL As Double) As MyColor
  292. If sS = 0 Then
  293. R = sL * 2.55
  294. G = R
  295. B = R
  296. Else
  297. Dim H = sH / 360
  298. Dim S = sS / 100
  299. Dim L = sL / 100
  300. S = If(L < 0.5, S * L + L, S * (1.0 - L) + L)
  301. L = 2 * L - S
  302. R = 255 * Hue(L, S, H + 1 / 3)
  303. G = 255 * Hue(L, S, H)
  304. B = 255 * Hue(L, S, H - 1 / 3)
  305. End If
  306. A = 255
  307. Return Me
  308. End Function
  309. Public Function FromHSL2(sH As Double, sS As Double, sL As Double) As MyColor
  310. If sS = 0 Then
  311. R = sL * 2.55 : G = R : B = R
  312. Else
  313. '初始化
  314. sH = (sH + 3600000) Mod 360
  315. Dim cent As Double() = {
  316. +0.1, -0.06, -0.3, '0, 30, 60
  317. -0.19, -0.15, -0.24, '90, 120, 150
  318. -0.32, -0.09, +0.18, '180, 210, 240
  319. +0.05, -0.12, -0.02, '270, 300, 330
  320. +0.1, -0.06} '最后两位与前两位一致,加是变亮,减是变暗
  321. '计算色调对应的亮度片区
  322. Dim center As Double = sH / 30.0
  323. Dim intCenter As Integer = Math.Floor(center) '亮度片区编号
  324. center = 50 - (
  325. (1 - center + intCenter) * cent(intCenter) + (center - intCenter) * cent(intCenter + 1)
  326. ) * sS
  327. 'center = 50 + (cent(intCenter) + (center - intCenter) * (cent(intCenter + 1) - cent(intCenter))) * sS
  328. sL = If(sL < center, sL / center, 1 + (sL - center) / (100 - center)) * 50
  329. FromHSL(sH, sS, sL)
  330. End If
  331. A = 255
  332. Return Me
  333. End Function
  334. Public Overrides Function ToString() As String
  335. Return "(" & A & "," & R & "," & G & "," & B & ")"
  336. End Function
  337. Public Overrides Function Equals(obj As Object) As Boolean
  338. Return Me = obj
  339. End Function
  340. End Class
  341. ''' <summary>
  342. ''' 支持负数与浮点数的矩形。
  343. ''' </summary>
  344. Public Class MyRect
  345. '属性
  346. Public Property Width As Double = 0
  347. Public Property Height As Double = 0
  348. Public Property Left As Double = 0
  349. Public Property Top As Double = 0
  350. '构造函数
  351. Public Sub New()
  352. End Sub
  353. Public Sub New(left As Double, top As Double, width As Double, height As Double)
  354. Me.Left = left
  355. Me.Top = top
  356. Me.Width = width
  357. Me.Height = height
  358. End Sub
  359. End Class
  360. ''' <summary>
  361. ''' 模块加载状态枚举。
  362. ''' </summary>
  363. Public Enum LoadState
  364. Waiting
  365. Loading
  366. Finished
  367. Failed
  368. Aborted
  369. End Enum
  370. ''' <summary>
  371. ''' 执行返回值。
  372. ''' </summary>
  373. Public Enum Result
  374. ''' <summary>
  375. ''' 执行成功,或进程被中断。
  376. ''' </summary>
  377. Aborted = -1
  378. ''' <summary>
  379. ''' 执行成功。
  380. ''' </summary>
  381. Success = 0
  382. ''' <summary>
  383. ''' 执行失败。
  384. ''' </summary>
  385. Fail
  386. ''' <summary>
  387. ''' 执行时出现未经处理的异常。
  388. ''' </summary>
  389. Exception
  390. ''' <summary>
  391. ''' 执行超时。
  392. ''' </summary>
  393. Timeout
  394. ''' <summary>
  395. ''' 取消执行。可能是由于不满足执行的前置条件。
  396. ''' </summary>
  397. Cancel
  398. End Enum
  399. ''' <summary>
  400. ''' 可以使用 Equals 和等号的 List。
  401. ''' </summary>
  402. Public Class EqualableList(Of T)
  403. Inherits List(Of T)
  404. Public Overrides Function Equals(obj As Object) As Boolean
  405. If TryCast(obj, List(Of T)) Is Nothing Then
  406. '类型不同
  407. Return False
  408. Else
  409. '类型相同
  410. Dim objList As List(Of T) = obj
  411. If objList.Count <> Count Then Return False
  412. For i = 0 To objList.Count - 1
  413. If Not objList(i).Equals(Me(i)) Then Return False
  414. Next
  415. Return True
  416. End If
  417. End Function
  418. Public Shared Operator =(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  419. Return EqualityComparer(Of EqualableList(Of T)).Default.Equals(left, right)
  420. End Operator
  421. Public Shared Operator <>(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  422. Return Not left = right
  423. End Operator
  424. End Class
  425. #End Region
  426. #Region "数学"
  427. ''' <summary>
  428. ''' 2~65 进制的转换。
  429. ''' </summary>
  430. Public Function RadixConvert(Input As String, FromRadix As Integer, ToRadix As Integer) As String
  431. Const Digits As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+="
  432. '零与负数的处理
  433. If String.IsNullOrEmpty(Input) Then Return "0"
  434. Dim IsNegative As Boolean = Input.StartsWith("-")
  435. If IsNegative Then Input = Input.TrimStart("-")
  436. '转换为十进制
  437. Dim RealNum As Long = 0, Scale As Long = 1
  438. For Each Digit In Input.Reverse.Select(Function(l) Digits.IndexOf(l))
  439. RealNum += Digit * Scale
  440. Scale *= FromRadix
  441. Next
  442. '转换为指定进制
  443. Dim Result = ""
  444. While RealNum > 0
  445. Dim NewNum As Integer = RealNum Mod ToRadix
  446. RealNum = (RealNum - NewNum) / ToRadix
  447. Result = Digits(NewNum) & Result
  448. End While
  449. '负数的结束处理与返回
  450. Return If(IsNegative, "-", "") & Result
  451. End Function
  452. ''' <summary>
  453. ''' 计算二阶贝塞尔曲线。
  454. ''' </summary>
  455. 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
  456. If x <= 0 OrElse Double.IsNaN(x) Then Return 0
  457. If x >= 1 Then Return 1
  458. Dim a, b
  459. a = x
  460. Do
  461. b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1)
  462. a += (x - b) * 0.5
  463. Loop Until Math.Abs(b - x) < acc '精度
  464. Return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1)
  465. End Function
  466. ''' <summary>
  467. ''' 将一个数字限制为 0~255 的 Byte 值。
  468. ''' </summary>
  469. Public Function MathByte(d As Double) As Byte
  470. If d < 0 Then d = 0
  471. If d > 255 Then d = 255
  472. Return Math.Round(d)
  473. End Function
  474. ''' <summary>
  475. ''' 提供 MyColor 类型支持的 Math.Round。
  476. ''' </summary>
  477. Public Function MathRound(col As MyColor, Optional w As Integer = 0) As MyColor
  478. 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)}
  479. End Function
  480. ''' <summary>
  481. ''' 获取两数间的百分比。小数点精确到 6 位。
  482. ''' </summary>
  483. ''' <returns></returns>
  484. ''' <remarks></remarks>
  485. Public Function MathPercent(ValueA As Double, ValueB As Double, Percent As Double) As Double
  486. Return Math.Round(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决 Double 计算错误
  487. End Function
  488. ''' <summary>
  489. ''' 获取两颜色间的百分比,根据 RGB 计算。小数点精确到 6 位。
  490. ''' </summary>
  491. Public Function MathPercent(ValueA As MyColor, ValueB As MyColor, Percent As Double) As MyColor
  492. Return MathRound(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决Double计算错误
  493. End Function
  494. ''' <summary>
  495. ''' 将数值限定在某个范围内。
  496. ''' </summary>
  497. Public Function MathRange(value As Double, min As Double, max As Double) As Double
  498. Return Math.Max(min, Math.Min(max, value))
  499. End Function
  500. ''' <summary>
  501. ''' 符号函数。
  502. ''' </summary>
  503. Public Function MathSgn(Value As Double) As Integer
  504. If Value = 0 Then
  505. Return 0
  506. ElseIf Value > 0 Then
  507. Return 1
  508. Else
  509. Return -1
  510. End If
  511. End Function
  512. #End Region
  513. #Region "文件"
  514. '注册表
  515. ''' <summary>
  516. ''' 重命名一个注册表子键。不可用于包含子键的子键。
  517. ''' </summary>
  518. Public Sub RegRename(parentKey As Microsoft.Win32.RegistryKey, subKeyName As String, newSubKeyName As String)
  519. If parentKey.GetSubKeyNames().Contains(newSubKeyName) Then parentKey.DeleteSubKeyTree(newSubKeyName, False)
  520. Dim SourceKey As Microsoft.Win32.RegistryKey = parentKey.OpenSubKey(subKeyName)
  521. If IsNothing(SourceKey) Then Exit Sub '没有目标项
  522. Dim NewKey As Microsoft.Win32.RegistryKey = parentKey.CreateSubKey(newSubKeyName)
  523. If SourceKey.GetSubKeyNames().Length > 0 Then Throw New NotSupportedException("不支持对包含子键的子键进行重命名:" & SourceKey.GetSubKeyNames()(0) & "。")
  524. For Each valueName As String In SourceKey.GetValueNames()
  525. Dim objValue As Object = SourceKey.GetValue(valueName)
  526. Dim valKind As Microsoft.Win32.RegistryValueKind = SourceKey.GetValueKind(valueName)
  527. NewKey.SetValue(valueName, objValue, valKind)
  528. Next
  529. parentKey.DeleteSubKeyTree(subKeyName, False)
  530. End Sub
  531. ''' <summary>
  532. ''' 读取程序所属注册表。
  533. ''' </summary>
  534. Public Function ReadReg(Key As String, Optional DefaultValue As String = "") As String
  535. Try
  536. Dim parentKey As Microsoft.Win32.RegistryKey, softKey As Microsoft.Win32.RegistryKey
  537. parentKey = My.Computer.Registry.CurrentUser
  538. softKey = parentKey.OpenSubKey("Software\PCL", True)
  539. If softKey Is Nothing Then
  540. ReadReg = DefaultValue '不存在则返回默认值
  541. Else
  542. Dim readValue As New Text.StringBuilder
  543. readValue.AppendLine(softKey.GetValue(Key))
  544. Dim value = readValue.ToString.Replace(vbCrLf, "") '去除莫名的回车
  545. Return If(value = "", DefaultValue, value) '错误则返回默认值
  546. End If
  547. Catch ex As Exception
  548. Log(ex, "读取注册表出错:" & Key, LogLevel.Hint)
  549. Return DefaultValue
  550. End Try
  551. End Function
  552. ''' <summary>
  553. ''' 写入程序所属注册表。
  554. ''' </summary>
  555. Public Sub WriteReg(Key As String, Value As String, Optional ShowException As Boolean = False)
  556. Try
  557. Dim parentKey As Microsoft.Win32.RegistryKey, softKey As Microsoft.Win32.RegistryKey
  558. parentKey = My.Computer.Registry.CurrentUser
  559. softKey = parentKey.OpenSubKey("Software\PCL", True)
  560. If softKey Is Nothing Then softKey = parentKey.CreateSubKey("Software\PCL") '如果不存在就创建
  561. softKey.SetValue(Key, Value)
  562. Catch ex As Exception
  563. Log(ex, "写入注册表出错:" & Key, If(ShowException, LogLevel.Hint, LogLevel.Developer))
  564. If ShowException Then Throw '如果显示错误就丢一个
  565. End Try
  566. End Sub
  567. 'Ini 文件
  568. Private Class IniCache
  569. Public FileContent As String = ""
  570. Public KVCache As New Dictionary(Of String, String)
  571. End Class
  572. Private ReadOnly IniCacheList As New Dictionary(Of String, IniCache)
  573. ''' <summary>
  574. ''' 清除某 Ini 文件的运行时缓存。
  575. ''' </summary>
  576. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  577. Public Sub IniClearCache(FileName As String)
  578. '还原文件路径
  579. If Not FileName.Contains(":\") Then FileName = Path & "PCL\" & FileName & ".ini"
  580. '检索缓存
  581. If IniCacheList.ContainsKey(FileName) Then IniCacheList.Remove(FileName)
  582. End Sub
  583. ''' <summary>
  584. ''' 获取 Ini 文件内容,这可能会使用到缓存。
  585. ''' </summary>
  586. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  587. Private Function IniGetContent(FileName As String) As IniCache
  588. Try
  589. '还原文件路径
  590. If Not FileName.Contains(":\") Then FileName = Path & "PCL\" & FileName & ".ini"
  591. '检索缓存
  592. If IniCacheList.ContainsKey(FileName) Then
  593. '返回缓存中的信息
  594. Dim Cache As New IniCache
  595. IniCacheList.TryGetValue(FileName, Cache)
  596. Return Cache '防止ByRef导致缓存变更
  597. Else
  598. Dim Ini As IniCache
  599. If File.Exists(FileName) Then
  600. '返回文件信息并且记入缓存
  601. Dim Cache As String = (vbCrLf & ReadFile(FileName) & vbCrLf).Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr, vbCrLf).Replace(vbCrLf & vbCrLf, vbCrLf).Replace(vbNullChar, "")
  602. Ini = New IniCache With {.FileContent = Cache}
  603. Else
  604. '返回空文件信息
  605. Ini = New IniCache With {.FileContent = ""}
  606. End If
  607. If Not IniCacheList.ContainsKey(FileName) Then IniCacheList.Add(FileName, Ini) '避免多线程异步执行此方法时造成多次添加项
  608. Return Ini
  609. End If
  610. Catch ex As Exception
  611. Log(ex, "读取文件失败:" & FileName, LogLevel.Hint)
  612. Return New IniCache With {.FileContent = ""}
  613. End Try
  614. End Function
  615. ''' <summary>
  616. ''' 读取Ini文件,这可能会使用到缓存。
  617. ''' </summary>
  618. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  619. ''' <param name="Key">键。</param>
  620. ''' <param name="DefaultValue">没有找到键时返回的默认值。</param>
  621. Public Function ReadIni(FileName As String, Key As String, Optional DefaultValue As String = "") As String
  622. Try
  623. '获取目前文件
  624. Dim NowIni As IniCache = IniGetContent(FileName)
  625. If IsNothing(NowIni) Then Return DefaultValue
  626. '使用缓存
  627. If NowIni.KVCache.ContainsKey(Key) Then Return If(NowIni.KVCache(Key), DefaultValue)
  628. '没有缓存,读取文件
  629. If NowIni.FileContent.Contains(vbCrLf & Key & ":") Then
  630. Dim Ret As String = Mid(NowIni.FileContent, NowIni.FileContent.IndexOf(vbCrLf & Key & ":") + 3)
  631. Ret = If(Ret.Contains(vbCrLf), Mid(Ret, 1, Ret.IndexOf(vbCrLf)), Ret).Replace(Key & ":", "")
  632. NowIni.KVCache.Add(Key, If(Ret = vbLf, "", Ret))
  633. Return If(Ret = vbLf, "", Ret)
  634. Else
  635. Return DefaultValue
  636. End If
  637. Catch ex As Exception
  638. '读取失败
  639. Return DefaultValue
  640. End Try
  641. End Function
  642. ''' <summary>
  643. ''' 写入ini文件,这会更新缓存。
  644. ''' </summary>
  645. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  646. ''' <param name="Key">键。</param>
  647. ''' <param name="Value">值。</param>
  648. ''' <remarks></remarks>
  649. Public Sub WriteIni(FileName As String, Key As String, Value As String)
  650. Try
  651. '还原文件路径
  652. If Not FileName.Contains(":\") Then FileName = Path & "PCL\" & FileName & ".ini"
  653. If IsNothing(Value) Then Value = ""
  654. Value = Value.Replace(vbCrLf, "")
  655. '创建文件夹
  656. If Not Directory.Exists(GetPathFromFullPath(FileName)) Then Directory.CreateDirectory(GetPathFromFullPath(FileName))
  657. '获取目前文件
  658. Dim NowFile As String = IniGetContent(FileName).FileContent
  659. If Not NowFile.EndsWith(vbCrLf) Then NowFile += vbCrLf
  660. '如果值一样就不处理
  661. If NowFile.Contains(vbCrLf & Key & ":" & Value & vbCrLf) Then Exit Sub
  662. '处理文件
  663. Dim FindResult As String = ReadIni(FileName, Key)
  664. If FindResult = "" AndAlso Not NowFile.Contains(vbCrLf & Key & ":") Then
  665. '不存在这个键
  666. NowFile = NowFile & vbCrLf & Key & ":" & Value & vbCrLf
  667. Else
  668. '存在这个键
  669. NowFile = NowFile.Replace(vbCrLf & Key & ":" & FindResult & vbCrLf, vbCrLf & Key & ":" & Value & vbCrLf)
  670. End If
  671. WriteFile(FileName, NowFile)
  672. '刷新目前缓存
  673. IniCacheList(FileName).FileContent = NowFile
  674. IniCacheList(FileName).KVCache.Remove(Key)
  675. IniCacheList(FileName).KVCache.Add(Key, Value)
  676. Catch ex As Exception
  677. Log(ex, "写入文件失败:" & FileName & "/" & Key & ": " & Value)
  678. End Try
  679. End Sub
  680. '路径处理
  681. ''' <summary>
  682. ''' 从文件路径或者 Url 获取不包含文件名的路径,或获取文件夹的父文件夹路径。不包含路径将会抛出异常。
  683. ''' </summary>
  684. Public Function GetPathFromFullPath(FilePath As String) As String
  685. If Not (FilePath.Contains("\") OrElse FilePath.Contains("/")) Then Throw New Exception("不包含路径:" & FilePath)
  686. If FilePath.EndsWith("\") OrElse FilePath.EndsWith("/") Then
  687. '是文件夹路径
  688. Dim IsRight As Boolean = FilePath.EndsWith("\")
  689. FilePath = Left(FilePath, Len(FilePath) - 1)
  690. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"})) & If(IsRight, "\", "/")
  691. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  692. Else
  693. '是文件路径
  694. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"}) + 1)
  695. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  696. End If
  697. End Function
  698. ''' <summary>
  699. ''' 从文件路径或者 Url 获取不包含路径的文件名。不包含文件名将会抛出异常。
  700. ''' </summary>
  701. Public Function GetFileNameFromPath(FilePath As String) As String
  702. If FilePath.EndsWith("\") OrElse FilePath.EndsWith("/") Then Throw New Exception("不包含文件名:" & FilePath)
  703. If Not (FilePath.Contains("\") OrElse FilePath.Contains("/")) Then Return FilePath
  704. If FilePath.Contains("?") Then FilePath = Left(FilePath, FilePath.LastIndexOf("?")) '去掉网络参数后的 ?
  705. GetFileNameFromPath = Mid(FilePath, FilePath.LastIndexOfAny({"\", "/"}) + 2)
  706. If GetFileNameFromPath = "" Then Throw New Exception("不包含文件名:" & FilePath)
  707. End Function
  708. ''' <summary>
  709. ''' 从文件路径或者 Url 获取不包含路径与扩展名的文件名。不包含文件名将会抛出异常。
  710. ''' </summary>
  711. Public Function GetFileNameWithoutExtentionFromPath(FilePath As String) As String
  712. Dim Name As String = GetFileNameFromPath(FilePath)
  713. If Name.Contains(".") Then
  714. Return Name.Substring(0, Name.LastIndexOf("."))
  715. Else
  716. Return Name
  717. End If
  718. End Function
  719. ''' <summary>
  720. ''' 从文件夹路径获取文件夹名。
  721. ''' </summary>
  722. Public Function GetFolderNameFromPath(FolderPath As String) As String
  723. If FolderPath.EndsWith(":\") OrElse FolderPath.EndsWith(":\\") Then Return FolderPath.Substring(0, 1)
  724. If FolderPath.EndsWith("\") OrElse FolderPath.EndsWith("/") Then FolderPath = Left(FolderPath, FolderPath.Length - 1)
  725. Return GetFileNameFromPath(FolderPath)
  726. End Function
  727. '读取、写入、复制文件
  728. Public Sub CopyFile(FromPath As String, ToPath As String)
  729. Try
  730. '还原文件路径
  731. If Not FromPath.Contains(":\") Then FromPath = Path & FromPath
  732. If Not ToPath.Contains(":\") Then ToPath = Path & ToPath
  733. '读取文件内容
  734. Dim FileBytes As Byte()
  735. Using ReadStream As New FileStream(FromPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) '支持读取使用中的文件
  736. ReDim FileBytes(ReadStream.Length - 1)
  737. ReadStream.Read(FileBytes, 0, ReadStream.Length)
  738. End Using
  739. '写入文件内容
  740. WriteFile(ToPath, FileBytes)
  741. Catch ex As Exception
  742. Throw New Exception("复制文件出错:" & FromPath & " -> " & ToPath, ex)
  743. End Try
  744. End Sub
  745. ''' <summary>
  746. ''' 读取文件,如果失败则返回空字符串。
  747. ''' </summary>
  748. ''' <param name="FilePath">文件完整或相对路径。</param>
  749. Public Function ReadFile(FilePath As String) As String
  750. Try
  751. '还原文件路径
  752. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  753. If File.Exists(FilePath) Then
  754. Dim FileBytes As Byte()
  755. Using ReadStream As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) '支持读取使用中的文件
  756. ReDim FileBytes(ReadStream.Length - 1)
  757. ReadStream.Read(FileBytes, 0, ReadStream.Length)
  758. End Using
  759. ReadFile = DecodeBytes(FileBytes)
  760. Else
  761. Log("[System] 欲读取的文件不存在,已返回空字符串:" & FilePath)
  762. Return ""
  763. End If
  764. Catch ex As Exception
  765. Log(ex, "读取文件出错:" & FilePath)
  766. Return ""
  767. End Try
  768. End Function
  769. ''' <summary>
  770. ''' 读取流中的所有文本。
  771. ''' </summary>
  772. Public Function ReadFile(Stream As Stream, Optional Encoding As Encoding = Nothing) As String
  773. Try
  774. Dim srcBuf As Byte() = New Byte(16384) {}
  775. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  776. Dim Result As New List(Of Byte)
  777. While DataCount > 0
  778. If DataCount > 0 Then Result.AddRange(srcBuf.ToList.GetRange(0, DataCount))
  779. DataCount = Stream.Read(srcBuf, 0, 16384)
  780. End While
  781. Dim Bts = Result.ToArray
  782. Return If(Encoding, GetEncoding(Bts)).GetString(Bts)
  783. Catch ex As Exception
  784. Log(ex, "读取流出错")
  785. Return ""
  786. End Try
  787. End Function
  788. ''' <summary>
  789. ''' 写入文件。
  790. ''' </summary>
  791. ''' <param name="FilePath">文件完整或相对路径。</param>
  792. ''' <param name="Text">文件内容。</param>
  793. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  794. Public Function WriteFile(FilePath As String, Text As String, Optional Append As Boolean = False, Optional Encoding As Encoding = Nothing) As Boolean
  795. Try
  796. '还原文件路径
  797. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  798. '确保目录存在
  799. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  800. '写入文件
  801. If File.Exists(FilePath) Then
  802. '如果文件存在,刷新目前文件
  803. Using writer As New StreamWriter(FilePath, Append, If(Encoding, GetEncoding(FilePath)))
  804. writer.Write(Text)
  805. writer.Flush()
  806. writer.Close()
  807. End Using
  808. Else
  809. '如果文件不存在,则新建并写入
  810. File.WriteAllText(FilePath, Text, If(Encoding, New UTF8Encoding(False)))
  811. End If
  812. Return True
  813. Catch ex As Exception
  814. Log(ex, "写入文件时出错:" & FilePath)
  815. Return False
  816. End Try
  817. End Function
  818. ''' <summary>
  819. ''' 写入文件。
  820. ''' </summary>
  821. ''' <param name="FilePath">文件完整或相对路径。</param>
  822. ''' <param name="Content">文件内容。</param>
  823. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  824. Public Function WriteFile(FilePath As String, Content As Byte(), Optional Append As Boolean = False) As Boolean
  825. Try
  826. '还原文件路径
  827. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  828. '确保目录存在
  829. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  830. '写入文件
  831. File.WriteAllBytes(FilePath, Content)
  832. Return True
  833. Catch ex As Exception
  834. Log(ex, "写入文件时出错:" & FilePath)
  835. Return False
  836. End Try
  837. End Function
  838. ''' <summary>
  839. ''' 将流写入文件。
  840. ''' </summary>
  841. ''' <param name="FilePath">文件完整或相对路径。</param>
  842. Public Function WriteFile(FilePath As String, Stream As Stream) As Boolean
  843. Try
  844. '还原文件路径
  845. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  846. '确保目录存在
  847. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  848. '读取流
  849. Using fs As New FileStream(FilePath, FileMode.Create, FileAccess.Write)
  850. Dim srcBuf As Byte() = New Byte(16384) {}
  851. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  852. While DataCount > 0
  853. If DataCount > 0 Then fs.Write(srcBuf, 0, DataCount)
  854. DataCount = Stream.Read(srcBuf, 0, 16384)
  855. End While
  856. fs.Close()
  857. End Using
  858. Return True
  859. Catch ex As Exception
  860. Log(ex, "保存流出错")
  861. Return False
  862. End Try
  863. End Function
  864. '文件编码
  865. ''' <summary>
  866. ''' 获取文件编码。
  867. ''' </summary>
  868. ''' <param name="FilePath">文件完整或相对路径。</param>
  869. Public Function GetEncoding(FilePath As String) As Encoding
  870. '还原文件路径
  871. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  872. '获取编码
  873. GetEncoding = GetEncoding(File.ReadAllBytes(FilePath))
  874. End Function
  875. ''' <summary>
  876. ''' 获取 Bytes 的编码。
  877. ''' </summary>
  878. Public Function GetEncoding(Bytes As Byte()) As Encoding
  879. Dim Length As Integer = Bytes.Count
  880. If Length <= 2 Then Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  881. '根据 BOM 判断编码
  882. If Bytes(0) >= &HEF Then
  883. '有 BOM 类型
  884. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  885. Return New UTF8Encoding(True) '带 BOM 的 UTF8
  886. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  887. Return Encoding.BigEndianUnicode
  888. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  889. Return Encoding.Unicode
  890. Else
  891. Return Encoding.GetEncoding("GB18030")
  892. End If
  893. End If
  894. '无 BOM 文件:GB18030(ANSI)或 UTF8
  895. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  896. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  897. If UTF8.Contains(ErrorChar) Then
  898. Return Encoding.GetEncoding("GB18030")
  899. Else
  900. Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  901. End If
  902. End Function
  903. ''' <summary>
  904. ''' 解码 Bytes。
  905. ''' </summary>
  906. Public Function DecodeBytes(Bytes As Byte()) As String
  907. Dim Length As Integer = Bytes.Length
  908. If Length < 3 Then Return Encoding.UTF8.GetString(Bytes)
  909. '根据 BOM 判断编码
  910. If Bytes(0) >= &HEF Then
  911. '有 BOM 类型
  912. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  913. Return Encoding.UTF8.GetString(Bytes, 3, Length - 3)
  914. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  915. Return Encoding.BigEndianUnicode.GetString(Bytes, 3, Length - 3)
  916. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  917. Return Encoding.Unicode.GetString(Bytes, 3, Length - 3)
  918. Else
  919. Return Encoding.GetEncoding("GB18030").GetString(Bytes, 3, Length - 3)
  920. End If
  921. End If
  922. '无 BOM 文件:GB18030(ANSI)或 UTF8
  923. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  924. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  925. If UTF8.Contains(ErrorChar) Then
  926. Return Encoding.GetEncoding("GB18030").GetString(Bytes)
  927. Else
  928. Return UTF8
  929. End If
  930. End Function
  931. '对话框
  932. ''' <summary>
  933. ''' 弹出保存对话框并且要求保存位置,返回用户输入的完整路径。
  934. ''' </summary>
  935. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  936. ''' <param name="Title">弹窗的标题。</param>
  937. ''' <param name="FileName">默认的文件名。</param>
  938. Public Function SelectAs(Title As String, FileName As String, Optional FileFilter As String = Nothing, Optional DefaultDir As String = Nothing) As String
  939. Using fileDialog As New Forms.SaveFileDialog
  940. fileDialog.AddExtension = True
  941. fileDialog.AutoUpgradeEnabled = True
  942. fileDialog.Title = Title
  943. fileDialog.FileName = FileName
  944. If FileFilter IsNot Nothing Then fileDialog.Filter = FileFilter
  945. If DefaultDir IsNot Nothing Then fileDialog.InitialDirectory = DefaultDir
  946. fileDialog.ShowDialog()
  947. SelectAs = If(fileDialog.FileName.Contains(":\"), fileDialog.FileName, "")
  948. Log("[UI] 选择文件返回:" & SelectAs)
  949. End Using
  950. End Function
  951. ''' <summary>
  952. ''' 弹出选取文件对话框并且要求选取文件。
  953. ''' </summary>
  954. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  955. ''' <param name="Title">弹窗的标题。</param>
  956. Public Function SelectFile(FileFilter As String, Title As String) As String
  957. Using fileDialog As New Forms.OpenFileDialog
  958. fileDialog.AddExtension = True
  959. fileDialog.AutoUpgradeEnabled = True
  960. fileDialog.CheckFileExists = True
  961. fileDialog.Filter = FileFilter
  962. fileDialog.Multiselect = False
  963. fileDialog.Title = Title
  964. fileDialog.ValidateNames = True
  965. fileDialog.ShowDialog()
  966. SelectFile = fileDialog.FileName
  967. Log("[UI] 选择文件返回:" & SelectFile)
  968. End Using
  969. End Function
  970. ''' <summary>
  971. ''' 弹出选取文件夹对话框并且要求选取文件夹。如果没有选择就返回空字符串。
  972. ''' </summary>
  973. Public Function SelectFolder(Optional Title As String = "选择文件夹") As String
  974. Dim folderDialog As New Ookii.Dialogs.Wpf.VistaFolderBrowserDialog With {.ShowNewFolderButton = True, .RootFolder = Environment.SpecialFolder.Desktop, .Description = Title, .UseDescriptionForTitle = True}
  975. folderDialog.ShowDialog()
  976. SelectFolder = If(String.IsNullOrEmpty(folderDialog.SelectedPath), "", folderDialog.SelectedPath & If(folderDialog.SelectedPath.EndsWith("\"), "", "\"))
  977. Log("[UI] 选择文件夹返回:" & SelectFolder)
  978. End Function
  979. '文件校验
  980. ''' <summary>
  981. ''' 检查是否拥有某一文件夹的 I/O 权限。如果文件夹不存在,会返回 False。
  982. ''' </summary>
  983. Public Function CheckPermission(Path As String) As Boolean
  984. Try
  985. If Path = "" Then Return False
  986. If Not Path.EndsWith("\") Then Path += "\"
  987. If Path.EndsWith(":\System Volume Information\") OrElse Path.EndsWith(":\$RECYCLE.BIN\") Then Return False
  988. If Not Directory.Exists(Path) Then Return False
  989. Dim FileName As String = "CheckPermission" & GetUuid()
  990. If File.Exists(Path & FileName) Then File.Delete(Path & FileName)
  991. File.Create(Path & FileName).Dispose()
  992. File.Delete(Path & FileName)
  993. Return True
  994. Catch ex As Exception
  995. Log(ex, "没有对文件夹 " & Path & " 的权限,请尝试以管理员权限运行 PCL")
  996. Return False
  997. End Try
  998. End Function
  999. ''' <summary>
  1000. ''' 检查是否拥有某一文件夹的 I/O 权限。如果出错,则抛出异常。
  1001. ''' </summary>
  1002. Public Sub CheckPermissionWithException(Path As String)
  1003. If String.IsNullOrWhiteSpace(Path) Then Throw New ArgumentNullException("文件夹名不能为空!")
  1004. If Not Path.EndsWith("\") Then Path += "\"
  1005. If Not Directory.Exists(Path) Then Throw New DirectoryNotFoundException("文件夹不存在!")
  1006. If File.Exists(Path & "CheckPermission") Then File.Delete(Path & "CheckPermission")
  1007. File.Create(Path & "CheckPermission").Dispose()
  1008. File.Delete(Path & "CheckPermission")
  1009. End Sub
  1010. ''' <summary>
  1011. ''' 获取文件 MD5,若失败则返回空字符串。
  1012. ''' </summary>
  1013. Public Function GetAuthMD5(FilePath As String) As String
  1014. Dim Retry As Boolean = False
  1015. Re:
  1016. Try
  1017. '获取 MD5
  1018. Dim Result As New StringBuilder()
  1019. Dim File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1020. Dim MD5 As MD5 = New MD5CryptoServiceProvider()
  1021. Dim Retval As Byte() = MD5.ComputeHash(File)
  1022. File.Close()
  1023. For i = 0 To Retval.Length - 1
  1024. Result.Append(Retval(i).ToString("x2"))
  1025. Next
  1026. Return Result.ToString
  1027. Catch ex As Exception
  1028. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1029. Log(ex, "获取文件 MD5 失败:" & FilePath)
  1030. Return ""
  1031. Else
  1032. Retry = True
  1033. Log(ex, "获取文件 MD5 可重试失败:" & FilePath, LogLevel.Normal)
  1034. Thread.Sleep(RandomInteger(200, 500))
  1035. GoTo Re
  1036. End If
  1037. End Try
  1038. End Function
  1039. ''' <summary>
  1040. ''' 获取文件 SHA256,若失败则返回空字符串。
  1041. ''' </summary>
  1042. Public Function GetAuthSHA256(FilePath As String) As String
  1043. Dim Retry As Boolean = False
  1044. Re:
  1045. Try
  1046. ''检测该文件是否在下载中,若在下载则放弃检测
  1047. 'If IgnoreOnDownloading AndAlso NetManage.Files.ContainsKey(FilePath) AndAlso NetManage.Files(FilePath).State <= NetState.Merge Then Return ""
  1048. '获取 SHA256
  1049. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1050. Dim sha1 As SHA256 = New SHA256CryptoServiceProvider()
  1051. Dim retval As Byte() = sha1.ComputeHash(file)
  1052. file.Close()
  1053. Dim Result As New StringBuilder()
  1054. For i As Integer = 0 To retval.Length - 1
  1055. Result.Append(retval(i).ToString("x2"))
  1056. Next
  1057. Return Result.ToString
  1058. Catch ex As Exception
  1059. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1060. Log(ex, "获取文件 SHA256 失败:" & FilePath)
  1061. Return ""
  1062. Else
  1063. Retry = True
  1064. Log(ex, "获取文件 SHA256 可重试失败:" & FilePath, LogLevel.Normal)
  1065. Thread.Sleep(RandomInteger(200, 500))
  1066. GoTo Re
  1067. End If
  1068. End Try
  1069. End Function
  1070. ''' <summary>
  1071. ''' 获取文件 SHA1,若失败则返回空字符串。
  1072. ''' </summary>
  1073. Public Function GetAuthSHA1(FilePath As String) As String
  1074. Dim Retry As Boolean = False
  1075. Re:
  1076. Try
  1077. ''检测该文件是否在下载中,若在下载则放弃检测
  1078. 'If IgnoreOnDownloading AndAlso NetManage.Files.ContainsKey(FilePath) AndAlso NetManage.Files(FilePath).State <= NetState.Merge Then Return ""
  1079. '获取 SHA1
  1080. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1081. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1082. Dim retval As Byte() = sha1.ComputeHash(file)
  1083. file.Close()
  1084. Dim Result As New StringBuilder()
  1085. For i As Integer = 0 To retval.Length - 1
  1086. Result.Append(retval(i).ToString("x2"))
  1087. Next
  1088. Return Result.ToString
  1089. Catch ex As Exception
  1090. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1091. Log(ex, "获取文件 SHA1 失败:" & FilePath)
  1092. Return ""
  1093. Else
  1094. Retry = True
  1095. Log(ex, "获取文件 SHA1 可重试失败:" & FilePath, LogLevel.Normal)
  1096. Thread.Sleep(RandomInteger(200, 500))
  1097. GoTo Re
  1098. End If
  1099. End Try
  1100. End Function
  1101. ''' <summary>
  1102. ''' 获取流 SHA1,若失败则返回空字符串。
  1103. ''' </summary>
  1104. Public Function GetAuthSHA1(Stream As Stream) As String
  1105. Try
  1106. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1107. Dim retval As Byte() = sha1.ComputeHash(Stream)
  1108. Dim Result As New StringBuilder()
  1109. For i As Integer = 0 To retval.Length - 1
  1110. Result.Append(retval(i).ToString("x2"))
  1111. Next
  1112. Return Result.ToString
  1113. Catch ex As Exception
  1114. Log(ex, "获取流 SHA1 失败")
  1115. Return ""
  1116. End Try
  1117. End Function
  1118. ''' <summary>
  1119. ''' 文件的校验规则。
  1120. ''' </summary>
  1121. Public Class FileChecker
  1122. ''' <summary>
  1123. ''' 文件的准确大小。
  1124. ''' </summary>
  1125. Public ActualSize As Long = -1
  1126. ''' <summary>
  1127. ''' 文件的最小大小。
  1128. ''' </summary>
  1129. Public MinSize As Long = -1
  1130. ''' <summary>
  1131. ''' 文件的 MD5、SHA1 或 SHA256。会根据输入字符串的长度自动判断种类。
  1132. ''' </summary>
  1133. Public Hash As String = Nothing
  1134. ''' <summary>
  1135. ''' 是否可以使用已经存在的文件。
  1136. ''' </summary>
  1137. Public CanUseExistsFile As Boolean = True
  1138. ''' <summary>
  1139. ''' 是否为 Json 文件。
  1140. ''' </summary>
  1141. Public IsJson As Boolean = False
  1142. 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)
  1143. Me.ActualSize = ActualSize
  1144. Me.MinSize = MinSize
  1145. Me.Hash = Hash
  1146. Me.CanUseExistsFile = CanUseExistsFile
  1147. Me.IsJson = IsJson
  1148. End Sub
  1149. ''' <summary>
  1150. ''' 检查文件。若成功则返回 Nothing,失败则返回错误的描述文本,描述文本不以句号结尾。不会抛出错误。
  1151. ''' </summary>
  1152. Public Function Check(LocalPath As String) As String
  1153. Try
  1154. Dim Info As New FileInfo(LocalPath)
  1155. If Not Info.Exists Then Return "文件不存在:" & LocalPath
  1156. Dim FileSize As Long = Info.Length
  1157. If ActualSize >= 0 AndAlso ActualSize <> FileSize Then Return "文件大小应为 " & ActualSize & " B,实际为 " & FileSize & " B"
  1158. If MinSize >= 0 AndAlso MinSize > FileSize Then Return "文件大小应大于 " & MinSize & " B,实际为 " & FileSize & " B"
  1159. If Not String.IsNullOrEmpty(Hash) Then
  1160. If Hash.Length < 35 Then 'MD5
  1161. If Hash <> GetAuthMD5(LocalPath) Then Return "文件 MD5 应为 " & Hash & ",实际为 " & GetAuthMD5(LocalPath)
  1162. ElseIf Hash.Length = 64 Then 'SHA256
  1163. If Hash <> GetAuthSHA256(LocalPath) Then Return "文件 SHA256 应为 " & Hash & ",实际为 " & GetAuthSHA256(LocalPath)
  1164. Else 'SHA1 (40)
  1165. If Hash <> GetAuthSHA1(LocalPath) Then Return "文件 SHA1 应为 " & Hash & ",实际为 " & GetAuthSHA1(LocalPath)
  1166. End If
  1167. End If
  1168. If IsJson Then
  1169. Dim Content As String = ReadFile(LocalPath)
  1170. If Content = "" Then Throw New Exception("读取到的文件为空")
  1171. Try
  1172. GetJson(Content)
  1173. Catch ex As Exception
  1174. Throw New Exception("不是有效的 Json 文件", ex)
  1175. End Try
  1176. End If
  1177. Return Nothing
  1178. Catch ex As Exception
  1179. Log(ex, "检查文件出错")
  1180. Return GetString(ex)
  1181. End Try
  1182. End Function
  1183. End Class
  1184. ''' <summary>
  1185. ''' 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  1186. ''' 会尝试创建,但不会清空目标文件夹。
  1187. ''' 成功返回 True,并非压缩文件或失败返回 False。
  1188. ''' </summary>
  1189. Public Function ExtractFile(CompressFilePath As String, DestDirectory As String, Optional Encode As Encoding = Nothing) As Boolean
  1190. Try
  1191. Directory.CreateDirectory(DestDirectory)
  1192. If CompressFilePath.EndsWith(".zip") OrElse CompressFilePath.EndsWith(".jar") Then
  1193. '以 zip 方式解压
  1194. ZipFile.ExtractToDirectory(CompressFilePath, DestDirectory, If(Encode, Encoding.Default))
  1195. Return True
  1196. ElseIf CompressFilePath.EndsWith(".gz") Then
  1197. '以 gz 方式解压
  1198. Dim stream As New GZipStream(New FileStream(CompressFilePath, FileMode.Open, FileAccess.ReadWrite), CompressionMode.Decompress)
  1199. Dim decompressedFile As New FileStream(DestDirectory & GetFileNameFromPath(CompressFilePath).ToLower.Replace(".tar", "").Replace(".gz", ""), FileMode.OpenOrCreate, FileAccess.Write)
  1200. Dim data As Integer = stream.ReadByte()
  1201. While data <> -1
  1202. decompressedFile.WriteByte(data)
  1203. data = stream.ReadByte()
  1204. End While
  1205. decompressedFile.Close()
  1206. stream.Close()
  1207. Return True
  1208. Else
  1209. Return False
  1210. End If
  1211. Catch ex As Exception
  1212. Log(ex, "尝试解压文件失败")
  1213. Return False
  1214. End Try
  1215. End Function
  1216. ''' <summary>
  1217. ''' 删除文件夹。失败会抛出异常。
  1218. ''' </summary>
  1219. Public Sub DeleteDirectory(Path As String, Optional IgnoreIssue As Boolean = False)
  1220. If Not Directory.Exists(Path) Then Exit Sub
  1221. Dim Temp As String()
  1222. Temp = Directory.GetFiles(Path)
  1223. For Each str As String In Temp
  1224. Try
  1225. File.Delete(str)
  1226. Catch ex As Exception
  1227. If IgnoreIssue Then
  1228. Log(ex, "删除单个文件可忽略地失败")
  1229. Else
  1230. Throw
  1231. End If
  1232. End Try
  1233. Next
  1234. Temp = Directory.GetDirectories(Path)
  1235. For Each str As String In Temp
  1236. DeleteDirectory(str)
  1237. Next
  1238. Try
  1239. Directory.Delete(Path, True)
  1240. Catch ex As Exception
  1241. If IgnoreIssue Then
  1242. Log(ex, "删除单个文件夹可忽略地失败")
  1243. Else
  1244. Throw
  1245. End If
  1246. End Try
  1247. '这个也不靠谱,目录不是空的警告
  1248. 'My.Computer.FileSystem.DeleteDirectory(Path, FileIO.DeleteDirectoryOption.DeleteAllContents)
  1249. End Sub
  1250. ''' <summary>
  1251. ''' 复制文件夹,失败会抛出异常。
  1252. ''' </summary>
  1253. Public Sub CopyDirectory(FromPath As String, ToPath As String)
  1254. For Each File In EnumerateFiles(FromPath)
  1255. CopyFile(File.FullName, File.FullName.Replace(FromPath, ToPath))
  1256. Next
  1257. End Sub
  1258. ''' <summary>
  1259. ''' 遍历文件夹中的所有文件。
  1260. ''' </summary>
  1261. Public Function EnumerateFiles(Directory As String) As List(Of FileInfo)
  1262. Dim Dir As New DirectoryInfo(Directory)
  1263. Dim ResultList As New List(Of FileInfo)
  1264. '添加文件
  1265. ResultList.AddRange(Dir.EnumerateFiles)
  1266. '添加文件夹中的文件
  1267. For Each SubDir In Dir.EnumerateDirectories
  1268. ResultList.AddRange(EnumerateFiles(SubDir.FullName))
  1269. Next
  1270. Return ResultList
  1271. End Function
  1272. #End Region
  1273. #Region "文本"
  1274. Public vbLQ As Char = Convert.ToChar(8220)
  1275. Public vbRQ As Char = Convert.ToChar(8221)
  1276. ''' <summary>
  1277. ''' 提取 Exception 摘要。
  1278. ''' </summary>
  1279. ''' <param name="IsLine">输出是否强制为单行,单行模型下不会输出调用堆栈。</param>
  1280. Public Function GetString(Ex As Exception, Optional IsLine As Boolean = True, Optional ShowAllTrace As Boolean = False) As String
  1281. If Ex Is Nothing Then Return "无可用错误信息!"
  1282. Dim Desc As New List(Of String)
  1283. '自动错误判断
  1284. Dim RealEx = Ex
  1285. Do Until RealEx.InnerException Is Nothing
  1286. RealEx = RealEx.InnerException
  1287. Loop
  1288. If TypeOf RealEx Is TypeLoadException OrElse TypeOf RealEx Is MissingMethodException OrElse TypeOf RealEx Is NotImplementedException OrElse TypeOf RealEx Is TypeInitializationException Then
  1289. Desc.Add("系统环境存在问题,请尝试重装 .Net Framework 4.6.2 后再试")
  1290. ElseIf TypeOf RealEx Is UnauthorizedAccessException Then
  1291. Desc.Add("PCL2 权限不足,请尝试右键 PCL2,选择以管理员身份运行")
  1292. ElseIf TypeOf RealEx Is OutOfMemoryException Then
  1293. Desc.Add("电脑运行内存不足,PCL2 无法继续运行")
  1294. End If
  1295. If IsLine Then
  1296. '无内部错误的快速处理
  1297. If Ex.InnerException Is Nothing Then
  1298. If Desc.Count = 0 Then
  1299. Return Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, " ")
  1300. Else
  1301. Return Desc.First
  1302. End If
  1303. End If
  1304. '构造输出信息
  1305. Do Until Ex Is Nothing
  1306. Desc.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, " "))
  1307. Ex = Ex.InnerException
  1308. Loop
  1309. Desc.Reverse() '让最深层错误在最左边
  1310. GetString = Join(Desc, " → ")
  1311. Else
  1312. Dim Stack As New List(Of String)
  1313. '逐级追加描述与堆栈
  1314. Do Until Ex Is Nothing
  1315. Desc.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, vbCrLf))
  1316. If Ex.StackTrace IsNot Nothing Then
  1317. For Each St As String In Ex.StackTrace.Split(vbCrLf)
  1318. If ShowAllTrace OrElse St.ToLower.Contains("pcl") Then Stack.Add(St.Replace(vbCr, String.Empty).Replace(vbLf, String.Empty))
  1319. Next
  1320. End If
  1321. Ex = Ex.InnerException
  1322. Loop
  1323. '构造输出信息
  1324. Dim TypeName As String = RealEx.GetType.FullName
  1325. GetString = Join(Desc, vbCrLf & "Caused By: ") & If(Stack.Count > 0, vbCrLf & Join(Stack, vbCrLf), "") & If(TypeName = "System.Exception", "", vbCrLf & "错误类型:" & TypeName)
  1326. End If
  1327. End Function
  1328. ''' <summary>
  1329. ''' 返回一个枚举对应的字符串。
  1330. ''' </summary>
  1331. ''' <param name="EnumData">一个已经实例化的枚举类型。</param>
  1332. Public Function GetStringFromEnum(EnumData As [Enum]) As String
  1333. Return [Enum].GetName(EnumData.GetType, EnumData)
  1334. End Function
  1335. ''' <summary>
  1336. ''' 将文件大小转化为适合的文本形式,如“1.28 M”。
  1337. ''' </summary>
  1338. ''' <param name="FileSize">以字节为单位的大小表示。</param>
  1339. Public Function GetString(FileSize As Long) As String
  1340. If FileSize < 1000 Then
  1341. 'B 级
  1342. Return FileSize & " B"
  1343. ElseIf FileSize < 1024 * 1000 Then
  1344. 'K 级
  1345. Dim RoundResult As String = Math.Round(FileSize / 1024)
  1346. Return Math.Round(FileSize / 1024, CInt(MathRange(3 - RoundResult.Length, 0, 2))) & " K"
  1347. ElseIf FileSize < 1024 * 1024 * 1000 Then
  1348. 'M 级
  1349. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024)
  1350. Return Math.Round(FileSize / 1024 / 1024, CInt(MathRange(3 - RoundResult.Length, 0, 2))) & " M"
  1351. Else
  1352. 'G 级
  1353. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024 / 1024)
  1354. Return Math.Round(FileSize / 1024 / 1024 / 1024, CInt(MathRange(3 - RoundResult.Length, 0, 2))) & " G"
  1355. End If
  1356. End Function
  1357. ''' <summary>
  1358. ''' 获取 Json 对象。
  1359. ''' </summary>
  1360. Public Function GetJson(Data As String)
  1361. Try
  1362. Return JsonConvert.DeserializeObject(Data, New JsonSerializerSettings With {.DateTimeZoneHandling = DateTimeZoneHandling.Local})
  1363. Catch ex As Exception
  1364. Throw New Exception("格式化 Json 对象失败:" & If(If(Data, "").Length > 10000, Data.Substring(0, 100) & "...", Data))
  1365. End Try
  1366. End Function
  1367. ''' <summary>
  1368. ''' 将字符串统一至某个长度,过短则以 Code 将其右侧填充,过长则截取靠左的指定长度。
  1369. ''' </summary>
  1370. Public Function StrFill(Str As String, Code As String, Length As Byte) As String
  1371. If Str.Length > Length Then Return Mid(Str, 1, Length)
  1372. Return Mid(Str.PadRight(Length, Code), Str.Length + 1) & Str
  1373. End Function
  1374. ''' <summary>
  1375. ''' 将一个小数显示为固定的小数点后位数形式,将向零取整。
  1376. ''' 如 12 保留 2 位则输出 12.00,而 95.678 保留 2 位则输出 95.67。
  1377. ''' </summary>
  1378. Public Function StrFillNum(Num As Double, Length As Integer) As String
  1379. Num = Math.Round(Num, Length, MidpointRounding.AwayFromZero)
  1380. StrFillNum = Num
  1381. If Not StrFillNum.Contains(".") Then Return (StrFillNum & ".").PadRight(StrFillNum.Length + 1 + Length, "0")
  1382. Return StrFillNum.PadRight(StrFillNum.Split(".")(0).Length + 1 + Length, "0")
  1383. End Function
  1384. ''' <summary>
  1385. ''' 移除字符串首尾的标点符号、回车,以及括号中、冒号后的补充说明内容。
  1386. ''' </summary>
  1387. Public Function StrTrim(Str As String, Optional RemoveQuote As Boolean = True)
  1388. If RemoveQuote Then Str = Str.Split("(")(0).Split(":")(0).Split("(")(0).Split(":")(0)
  1389. Return Str.Trim(".", "。", "!", " ", "!", "?", "?", vbCr, vbLf)
  1390. End Function
  1391. ''' <summary>
  1392. ''' 连接字符串。
  1393. ''' </summary>
  1394. Public Function Join(List As ICollection, Split As String) As String
  1395. Dim Builder As New StringBuilder
  1396. Dim LastCount As Integer = List.Count - 1
  1397. For i = 0 To LastCount
  1398. If List(i) IsNot Nothing Then Builder.Append(List(i))
  1399. If i <> LastCount Then Builder.Append(Split)
  1400. Next
  1401. Return Builder.ToString
  1402. End Function
  1403. ''' <summary>
  1404. ''' 获取字符串哈希值。
  1405. ''' </summary>
  1406. Public Function GetHash(Str As String) As ULong
  1407. GetHash = 5381
  1408. For i = 0 To Str.Length - 1
  1409. GetHash = (GetHash << 5) Xor GetHash Xor CType(AscW(Str(i)), ULong)
  1410. Next
  1411. Return GetHash Xor &HA98F501BC684032FUL
  1412. End Function
  1413. ''' <summary>
  1414. ''' 获取字符串 MD5。
  1415. ''' </summary>
  1416. Public Function GetStringMD5(Str As String) As String
  1417. Dim md5Hasher As New MD5CryptoServiceProvider
  1418. Dim hashedDataBytes As Byte()
  1419. hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(Str))
  1420. Dim tmp As New StringBuilder()
  1421. For Each i As Byte In hashedDataBytes
  1422. tmp.Append(i.ToString("x2"))
  1423. Next
  1424. Return tmp.ToString()
  1425. End Function
  1426. ''' <summary>
  1427. ''' 输入 And 字符不会报错的 Val。
  1428. ''' </summary>
  1429. Public Function Val(Str As Object) As Double
  1430. Return If(TypeOf Str Is String AndAlso Str = "&", 0, Conversion.Val(Str))
  1431. End Function
  1432. '转义
  1433. ''' <summary>
  1434. ''' 为字符串进行 XML 转义。
  1435. ''' </summary>
  1436. Public Function EscapeXML(Str As String) As String
  1437. Return Str.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;").Replace("""", "&quot;")
  1438. End Function
  1439. '正则
  1440. ''' <summary>
  1441. ''' 搜索字符串中的所有正则匹配项。
  1442. ''' </summary>
  1443. Public Function RegexSearch(str As String, regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As List(Of String)
  1444. Try
  1445. RegexSearch = New List(Of String)
  1446. Dim RegexSearchRes = New RegularExpressions.Regex(regex, options).Matches(str)
  1447. If RegexSearchRes Is Nothing Then Return RegexSearch
  1448. For Each item As RegularExpressions.Match In RegexSearchRes
  1449. RegexSearch.Add(item.Value)
  1450. Next
  1451. Catch ex As Exception
  1452. Log(ex, "正则匹配全部项出错")
  1453. Return New List(Of String)
  1454. End Try
  1455. End Function
  1456. ''' <summary>
  1457. ''' 获取字符串中的第一个正则匹配项,若无匹配则返回 Nothing。
  1458. ''' </summary>
  1459. Public Function RegexSeek(str As String, regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As String
  1460. Try
  1461. Dim Result = RegularExpressions.Regex.Match(str, regex, options).Value
  1462. Return If(Result = "", Nothing, Result)
  1463. Catch ex As Exception
  1464. Log(ex, "正则匹配第一项出错")
  1465. Return Nothing
  1466. End Try
  1467. End Function
  1468. ''' <summary>
  1469. ''' 检查字符串是否匹配某正则模式。
  1470. ''' </summary>
  1471. Public Function RegexCheck(str As String, regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As Boolean
  1472. Try
  1473. Return RegularExpressions.Regex.IsMatch(str, regex, options)
  1474. Catch ex As Exception
  1475. Log(ex, "正则检查出错")
  1476. Return False
  1477. End Try
  1478. End Function
  1479. ''' <summary>
  1480. ''' 进行正则替换,会抛出错误。
  1481. ''' </summary>
  1482. Public Function RegexReplace(Input As String, Replacement As String, Regex As String, Optional options As RegularExpressions.RegexOptions = RegularExpressions.RegexOptions.None) As String
  1483. Return RegularExpressions.Regex.Replace(Input, Regex, Replacement, options)
  1484. End Function
  1485. #End Region
  1486. #Region "搜索"
  1487. ''' <summary>
  1488. ''' 获取搜索文本的相似度。
  1489. ''' </summary>
  1490. ''' <param name="Source">被搜索的长内容。</param>
  1491. ''' <param name="Query">用户输入的搜索文本。</param>
  1492. Private Function SearchSimilarity(Source As String, Query As String) As Double
  1493. Dim qp As Integer = 0, lenSum As Double = 0
  1494. Source = Source.ToLower.Replace(" ", "")
  1495. Query = Query.ToLower.Replace(" ", "")
  1496. Dim sourceLength As Integer = Source.Length, queryLength As Integer = Query.Length '用于计算最后因数的长度缓存
  1497. Do While qp < Query.Length
  1498. '对 qp 作为开始位置计算
  1499. Dim sp As Integer = 0, lenMax As Integer = 0, spMax As Integer = 0
  1500. '查找以 qp 为头的最大子串
  1501. Do While sp < Source.Length
  1502. '对每个 sp 作为开始位置计算最大子串
  1503. Dim len As Integer = 0
  1504. Do While (qp + len) < Query.Length AndAlso (sp + len) < Source.Length AndAlso Source(sp + len) = Query(qp + len)
  1505. len += 1
  1506. Loop
  1507. '存储 len
  1508. If len > lenMax Then
  1509. lenMax = len
  1510. spMax = sp
  1511. End If
  1512. '根据结果增加 sp
  1513. sp += Math.Max(1, len)
  1514. Loop
  1515. If lenMax > 0 Then
  1516. Source = Source.Substring(0, spMax) & If(Source.Count > spMax + lenMax, Source.Substring(spMax + lenMax), String.Empty) '将源中的对应字段替换空
  1517. '存储 lenSum
  1518. Dim IncWeight = (Math.Pow(1.4, 3 + lenMax) - 3.6) '根据长度加成
  1519. IncWeight *= (1 + 0.3 * Math.Max(0, 3 - Math.Abs(qp - spMax))) '根据位置加成
  1520. lenSum += IncWeight
  1521. End If
  1522. '根据结果增加 qp
  1523. qp += Math.Max(1, lenMax)
  1524. Loop
  1525. '计算结果:重复字段量 × 源长度影响比例
  1526. Return (lenSum / queryLength) * (3 / Math.Pow(sourceLength + 15, 0.5)) * If(queryLength <= 2, 3 - queryLength, 1)
  1527. End Function
  1528. ''' <summary>
  1529. ''' 获取多段文本加权后的相似度。
  1530. ''' </summary>
  1531. Private Function SearchSimilarityWeighted(Source As List(Of KeyValuePair(Of String, Double)), Query As String) As Double
  1532. Dim TotalWeight As Double = 0
  1533. Dim Sum As Double = 0
  1534. For Each Pair In Source
  1535. Sum += SearchSimilarity(Pair.Key, Query) * Pair.Value
  1536. TotalWeight += Pair.Value
  1537. Next
  1538. Return Sum / TotalWeight
  1539. End Function
  1540. ''' <summary>
  1541. ''' 用于搜索的项目。
  1542. ''' </summary>
  1543. Public Class SearchEntry(Of T)
  1544. ''' <summary>
  1545. ''' 该项目对应的源数据。
  1546. ''' </summary>
  1547. Public Item As T
  1548. ''' <summary>
  1549. ''' 该项目用于搜索的源。
  1550. ''' </summary>
  1551. Public SearchSource As List(Of KeyValuePair(Of String, Double))
  1552. ''' <summary>
  1553. ''' 相似度。
  1554. ''' </summary>
  1555. Public Similarity As Double
  1556. ''' <summary>
  1557. ''' 是否完全匹配。
  1558. ''' </summary>
  1559. Public AbsoluteRight As Boolean
  1560. End Class
  1561. ''' <summary>
  1562. ''' 进行多段文本加权搜索,获取相似度较高的数项结果。
  1563. ''' </summary>
  1564. ''' <param name="MaxBlurCount">返回的最大模糊结果数。</param>
  1565. ''' <param name="MinBlurSimilarity">返回结果要求的最低相似度。</param>
  1566. 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))
  1567. '初始化
  1568. Dim ResultList As New List(Of SearchEntry(Of T))
  1569. If Entries.Count = 0 Then Return ResultList
  1570. '进行搜索,获取相似信息
  1571. For Each Entry In Entries
  1572. Entry.Similarity = SearchSimilarityWeighted(Entry.SearchSource, Query)
  1573. Entry.AbsoluteRight = False
  1574. For Each Pair In Entry.SearchSource
  1575. If Pair.Key.ToLower.Replace(" ", "").Contains(Query.ToLower.Replace(" ", "")) Then Entry.AbsoluteRight = True
  1576. Next
  1577. Next
  1578. '按照相似度进行排序
  1579. Entries = Sort(Entries, Function(Left As SearchEntry(Of T), Right As SearchEntry(Of T)) As Boolean
  1580. If Left.AbsoluteRight Xor Right.AbsoluteRight Then
  1581. Return Left.AbsoluteRight
  1582. Else
  1583. Return Left.Similarity > Right.Similarity
  1584. End If
  1585. End Function)
  1586. '返回结果
  1587. Dim BlurCount As Integer = 0
  1588. For Each Entry In Entries
  1589. If Entry.AbsoluteRight Then
  1590. ResultList.Add(Entry) '完全匹配,直接加入
  1591. Else
  1592. If Entry.Similarity < MinBlurSimilarity OrElse BlurCount = MaxBlurCount Then Exit For '模糊结果边界条件
  1593. ResultList.Add(Entry)
  1594. BlurCount += 1 '模糊结果计数
  1595. End If
  1596. Next
  1597. Return ResultList
  1598. End Function
  1599. #End Region
  1600. #Region "系统"
  1601. ''' <summary>
  1602. ''' 当前程序是否拥有管理员权限。
  1603. ''' </summary>
  1604. Public Function IsAdmin() As Boolean
  1605. Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
  1606. Dim principal As New WindowsPrincipal(id)
  1607. Return principal.IsInRole(WindowsBuiltInRole.Administrator)
  1608. End Function
  1609. ''' <summary>
  1610. ''' 以管理员权限重新运行当前程序。返回是否成功。
  1611. ''' </summary>
  1612. Public Function RerunAsAdmin(Argument As String) As Boolean
  1613. Try
  1614. Process.Start(New ProcessStartInfo(PathWithName) With {.Verb = "runas", .Arguments = Argument})
  1615. Return True
  1616. Catch ex As Exception
  1617. Log(ex, "以管理员权限运行程序失败")
  1618. Return False
  1619. End Try
  1620. End Function
  1621. Private Uuid As Integer = 1
  1622. Private UuidLock As Object
  1623. ''' <summary>
  1624. ''' 获取一个全程序内不会重复的数字(伪 Uuid)。
  1625. ''' </summary>
  1626. Public Function GetUuid() As Integer
  1627. If UuidLock Is Nothing Then UuidLock = New Object
  1628. SyncLock UuidLock
  1629. Uuid += 1
  1630. Return Uuid
  1631. End SyncLock
  1632. End Function
  1633. ''' <summary>
  1634. ''' 将元素与 List 的混合体拆分为元素组。
  1635. ''' </summary>
  1636. Public Function GetFullList(Of T)(data As IList) As List(Of T)
  1637. GetFullList = New List(Of T)
  1638. For i = 0 To data.Count - 1
  1639. If TypeOf data(i) Is ICollection Then
  1640. GetFullList.AddRange(data(i))
  1641. Else
  1642. GetFullList.Add(data(i))
  1643. End If
  1644. Next i
  1645. End Function
  1646. ''' <summary>
  1647. ''' 数组去重。
  1648. ''' </summary>
  1649. Public Function ArrayNoDouble(Of T)(Arr As T(), Optional IsEqual As CompareThreadStart = Nothing) As T()
  1650. Dim ResultArray As New List(Of T)
  1651. For i = 0 To UBound(Arr)
  1652. For ii = i + 1 To UBound(Arr)
  1653. If IsEqual Is Nothing Then
  1654. If Arr(i).Equals(Arr(ii)) Then GoTo NextElement
  1655. Else
  1656. If IsEqual(Arr(i), Arr(ii)) Then GoTo NextElement
  1657. End If
  1658. Next
  1659. ResultArray.Add(Arr(i))
  1660. NextElement:
  1661. Next i
  1662. Return ResultArray.ToArray
  1663. End Function
  1664. ''' <summary>
  1665. ''' 数组去重。
  1666. ''' </summary>
  1667. Public Function ArrayNoDouble(Of T)(Arr As List(Of T), Optional IsEqual As CompareThreadStart = Nothing) As List(Of T)
  1668. Dim ResultArray As New List(Of T)
  1669. For i = 0 To Arr.Count - 1
  1670. For ii = i + 1 To Arr.Count - 1
  1671. If IsEqual Is Nothing Then
  1672. If Arr(i).Equals(Arr(ii)) Then GoTo NextElement
  1673. Else
  1674. If IsEqual(Arr(i), Arr(ii)) Then GoTo NextElement
  1675. End If
  1676. Next
  1677. ResultArray.Add(Arr(i))
  1678. NextElement:
  1679. Next i
  1680. Return ResultArray
  1681. End Function
  1682. ''' <summary>
  1683. ''' 若 Key 不存在于辞典,则加入辞典。
  1684. ''' 若 Key 已存在于辞典,则更新 Value。
  1685. ''' </summary>
  1686. Public Sub DictionaryAdd(Of TKey, TValue)(ByRef Dict As Dictionary(Of TKey, TValue), Key As TKey, Value As TValue)
  1687. If Dict.ContainsKey(Key) Then
  1688. Dict(Key) = Value
  1689. Else
  1690. Dict.Add(Key, Value)
  1691. End If
  1692. End Sub
  1693. ''' <summary>
  1694. ''' 获取格式类似于“11:08:52.037”的当前时间的字符串。
  1695. ''' </summary>
  1696. Public Function GetTimeNow() As String
  1697. Return Date.Now.ToString("HH:mm:ss.fff")
  1698. End Function
  1699. ''' <summary>
  1700. ''' 获取系统运行时间(毫秒),保证为正 Long 且大于 1,但可能突变减小。
  1701. ''' </summary>
  1702. Public Function GetTimeTick() As Long
  1703. Return My.Computer.Clock.TickCount + 2147483651L
  1704. End Function
  1705. ''' <summary>
  1706. ''' 将时间间隔转换为类似“5 分 10 秒前”的易于阅读的形式。
  1707. ''' </summary>
  1708. Public Function GetTimeSpanString(Span As TimeSpan) As String
  1709. Dim EndFix = If(Span.TotalMilliseconds > 0, "后", "前")
  1710. If Span.TotalMilliseconds < 0 Then Span = -Span
  1711. Dim TotalMonthes = Math.Floor(Span.Days / 30)
  1712. If TotalMonthes >= 61 Then
  1713. '5+ 年,“5 年”
  1714. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  1715. ElseIf TotalMonthes >= 12 Then
  1716. '12~60 月,“1 年 2 个月”
  1717. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年" & If((TotalMonthes Mod 12) > 0, " " & (TotalMonthes Mod 12) & " 个月", "")
  1718. ElseIf TotalMonthes >= 4 Then
  1719. '4~11 月,“5 月”
  1720. GetTimeSpanString = TotalMonthes & " 月"
  1721. ElseIf TotalMonthes >= 1 Then
  1722. '1~4 月,“2 月 13 天”
  1723. GetTimeSpanString = TotalMonthes & " 月" & If((Span.Days Mod 30) > 0, " " & (Span.Days Mod 30) & " 天", "")
  1724. ElseIf Span.TotalDays >= 4 Then
  1725. '4~30 天,“23 天”
  1726. GetTimeSpanString = Span.Days & " 天"
  1727. ElseIf Span.TotalDays >= 1 Then
  1728. '1~3 天,“2 天 20 小时”
  1729. GetTimeSpanString = Span.Days & " 天" & If(Span.Hours > 0, " " & Span.Hours & " 小时", "")
  1730. ElseIf Span.TotalHours >= 10 Then
  1731. '10 小时 ~ 1 天,“15 小时”
  1732. GetTimeSpanString = Span.Hours & " 小时"
  1733. ElseIf Span.TotalHours >= 1 Then
  1734. '1~10 小时,“1 小时 20 分钟”
  1735. GetTimeSpanString = Span.Hours & " 小时" & If(Span.Minutes > 0, " " & Span.Minutes & " 分钟", "")
  1736. ElseIf Span.TotalMinutes >= 10 Then
  1737. '10 分钟 ~ 1 小时,“49 分钟”
  1738. GetTimeSpanString = Span.Minutes & " 分钟"
  1739. ElseIf Span.TotalMinutes >= 1 Then
  1740. '1~10 分钟,“9 分 23 秒”
  1741. GetTimeSpanString = Span.Minutes & " 分" & If(Span.Seconds > 0, " " & Span.Seconds & " 秒", "")
  1742. ElseIf Span.TotalSeconds >= 1 Then
  1743. '1 秒 ~ 1 分钟,“23 秒”
  1744. GetTimeSpanString = Span.Seconds & " 秒"
  1745. Else
  1746. '不到 1 秒
  1747. GetTimeSpanString = "1 秒"
  1748. End If
  1749. GetTimeSpanString += EndFix
  1750. End Function
  1751. ''' <summary>
  1752. ''' 获取十进制 Unix 时间戳。
  1753. ''' </summary>
  1754. Public Function GetUnixTimestamp() As Long
  1755. Return (Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000
  1756. End Function
  1757. ''' <summary>
  1758. ''' 用于储存 RaiseByMouse 的 EventArgs。
  1759. ''' </summary>
  1760. Public NotInheritable Class RouteEventArgs
  1761. Inherits EventArgs
  1762. Public RaiseByMouse As Boolean
  1763. Public Handled As Boolean = False
  1764. Public Sub New(Optional RaiseByMouse As Boolean = False)
  1765. Me.RaiseByMouse = RaiseByMouse
  1766. End Sub
  1767. End Class
  1768. ''' <summary>
  1769. ''' 前台运行文件。
  1770. ''' </summary>
  1771. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1772. ''' <param name="Arguments">运行参数。</param>
  1773. Public Sub ShellOnly(FileName As String, Optional Arguments As String = "")
  1774. Using Program As New Process
  1775. Program.StartInfo.Arguments = Arguments
  1776. Program.StartInfo.FileName = FileName
  1777. Log("[System] 执行外部命令:" & FileName & " " & Arguments)
  1778. Program.Start()
  1779. End Using
  1780. End Sub
  1781. ''' <summary>
  1782. ''' 前台运行文件并返回返回值。
  1783. ''' </summary>
  1784. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1785. ''' <param name="Arguments">运行参数。</param>
  1786. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会返回 Result.Timeout。</param>
  1787. Public Function ShellAndGetExitCode(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000) As Result
  1788. Try
  1789. Using Program As New Process
  1790. Program.StartInfo.Arguments = Arguments
  1791. Program.StartInfo.FileName = FileName
  1792. Log("[System] 执行外部命令并等待返回码:" & FileName & " " & Arguments)
  1793. Program.Start()
  1794. If Program.WaitForExit(Timeout) Then
  1795. Return Program.ExitCode
  1796. Else
  1797. Return Result.Timeout
  1798. End If
  1799. End Using
  1800. Catch ex As Exception
  1801. Log(ex, "执行命令失败:" & FileName, LogLevel.Msgbox)
  1802. Return Result.Fail
  1803. End Try
  1804. End Function
  1805. ''' <summary>
  1806. ''' 静默运行文件并返回输出流字符串。执行失败会抛出异常。
  1807. ''' </summary>
  1808. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1809. ''' <param name="Arguments">运行参数。</param>
  1810. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会抛出错误。</param>
  1811. Public Function ShellAndGetOutput(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000, Optional WorkingDirectory As String = Nothing) As String
  1812. Dim Info = New ProcessStartInfo With {
  1813. .Arguments = Arguments,
  1814. .FileName = FileName,
  1815. .UseShellExecute = False,
  1816. .CreateNoWindow = True,
  1817. .RedirectStandardError = True,
  1818. .RedirectStandardOutput = True,
  1819. .WorkingDirectory = If(WorkingDirectory, Path.TrimEnd("\"c))
  1820. }
  1821. If WorkingDirectory IsNot Nothing Then
  1822. If Info.EnvironmentVariables.ContainsKey("appdata") Then
  1823. Info.EnvironmentVariables("appdata") = WorkingDirectory
  1824. Else
  1825. Info.EnvironmentVariables.Add("appdata", WorkingDirectory)
  1826. End If
  1827. End If
  1828. Log("[System] 执行外部命令并等待返回结果:" & FileName & " " & Arguments)
  1829. Using Program As New Process() With {.StartInfo = Info}
  1830. Program.Start()
  1831. Program.WaitForExit(Timeout)
  1832. Return Program.StandardOutput.ReadToEnd & Program.StandardError.ReadToEnd
  1833. ' Dim Result As New StringBuilder()
  1834. ' AddHandler process.OutputDataReceived, Function(sender As Object, e As DataReceivedEventArgs)
  1835. ' Try
  1836. ' If e.Data IsNot Nothing Then Result.AppendLine(e.Data)
  1837. ' Finally
  1838. ' End Try
  1839. ' Return Nothing
  1840. ' End Function
  1841. ' AddHandler process.ErrorDataReceived, Function(sender As Object, e As DataReceivedEventArgs)
  1842. ' Try
  1843. ' If e.Data IsNot Nothing Then Result.AppendLine(e.Data)
  1844. ' Finally
  1845. ' End Try
  1846. ' Return Nothing
  1847. ' End Function
  1848. ' process.Start()
  1849. ' process.BeginOutputReadLine()
  1850. ' process.BeginErrorReadLine()
  1851. ' If process.WaitForExit(Timeout) Then
  1852. ' process.Close()
  1853. ' Return Result.ToString
  1854. ' Else
  1855. ' process.Close()
  1856. ' Throw New TimeoutException("程序执行超时,已有返回值:" & Result.ToString)
  1857. ' End If
  1858. End Using
  1859. End Function
  1860. ''' <summary>
  1861. ''' 在新的工作线程中执行代码。
  1862. ''' </summary>
  1863. Public Function RunInNewThread(Action As Action, Name As String, Optional Priority As ThreadPriority = ThreadPriority.Normal) As Thread
  1864. Dim th As New Thread(Sub()
  1865. Try
  1866. Action()
  1867. Catch ex As ThreadInterruptedException
  1868. Log(Name & ":线程已中止")
  1869. Catch ex As Exception
  1870. Log(ex, Name & ":线程执行失败", LogLevel.Feedback)
  1871. End Try
  1872. End Sub) With {.Name = Name, .Priority = Priority}
  1873. th.Start()
  1874. Return th
  1875. End Function
  1876. ''' <summary>
  1877. ''' 确保在 UI 线程中执行代码。
  1878. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  1879. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  1880. ''' </summary>
  1881. Public Function RunInUiWait(Of Output)(Action As Func(Of Output)) As Output
  1882. If RunInUi() Then
  1883. Return Action()
  1884. Else
  1885. Return Application.Current.Dispatcher.Invoke(Action)
  1886. End If
  1887. End Function
  1888. ''' <summary>
  1889. ''' 确保在 UI 线程中执行代码。
  1890. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  1891. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  1892. ''' </summary>
  1893. Public Sub RunInUiWait(Action As Action)
  1894. If RunInUi() Then
  1895. Action()
  1896. Else
  1897. Application.Current.Dispatcher.Invoke(Action)
  1898. End If
  1899. End Sub
  1900. ''' <summary>
  1901. ''' 确保在 UI 线程中执行代码,代码按触发顺序执行。
  1902. ''' 如果当前并非 UI 线程,也不阻断当前线程的执行。
  1903. ''' </summary>
  1904. Public Sub RunInUi(Action As Action, Optional ForceWaitUntilLoaded As Boolean = False)
  1905. If ForceWaitUntilLoaded Then
  1906. Application.Current.Dispatcher.InvokeAsync(Action, Threading.DispatcherPriority.Loaded)
  1907. ElseIf RunInUi() Then
  1908. Action()
  1909. Else
  1910. Application.Current.Dispatcher.InvokeAsync(Action)
  1911. End If
  1912. End Sub
  1913. ''' <summary>
  1914. ''' 确保在工作线程中执行代码。
  1915. ''' </summary>
  1916. Public Sub RunInThread(Action As Action)
  1917. If RunInUi() Then
  1918. RunInNewThread(Action, "Runtime Invoke " & GetUuid() & "#")
  1919. Else
  1920. Action()
  1921. End If
  1922. End Sub
  1923. ''' <summary>
  1924. ''' 按照既定的函数进行选择排序。
  1925. ''' </summary>
  1926. ''' <param name="SortRule">传入两个对象,若第一个对象应该排在前面,则返回 True。</param>
  1927. Public Function Sort(Of T)(List As IList(Of T), SortRule As CompareThreadStart) As List(Of T)
  1928. Dim NewList As New List(Of T)
  1929. While List.Count > 0
  1930. Dim Highest = List(0)
  1931. For i = 1 To List.Count - 1
  1932. If SortRule(List(i), Highest) Then Highest = List(i)
  1933. Next
  1934. List.Remove(Highest)
  1935. NewList.Add(Highest)
  1936. End While
  1937. Return NewList
  1938. End Function
  1939. Public Delegate Function CompareThreadStart(Left, Right) As Boolean
  1940. ''' <summary>
  1941. ''' 获取程序启动参数。
  1942. ''' </summary>
  1943. ''' <param name="Name">参数名。</param>
  1944. ''' <param name="DefaultValue">默认值。</param>
  1945. Public Function GetProgramArgument(Name As String, Optional DefaultValue As Object = "")
  1946. Dim AllArguments() As String = Command.Split(" ")
  1947. For i = 0 To AllArguments.Length - 1
  1948. If AllArguments(i) = "-" & Name Then
  1949. If AllArguments.Length = i + 1 OrElse AllArguments(i + 1).StartsWith("-") Then Return True
  1950. Return AllArguments(i + 1)
  1951. End If
  1952. Next
  1953. Return DefaultValue
  1954. End Function
  1955. ''' <summary>
  1956. ''' 时间戳转化为日期。
  1957. ''' </summary>
  1958. Public Function GetDate(timeStamp As Integer) As Date
  1959. Dim dtStart As Date = TimeZone.CurrentTimeZone.ToLocalTime(New Date(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
  1960. Dim lTime As Long = (CLng(timeStamp) * 10000000)
  1961. Return dtStart.Add(New TimeSpan(lTime))
  1962. End Function
  1963. ''' <summary>
  1964. ''' 将 UTC 时间转化为当前时区的时间。
  1965. ''' </summary>
  1966. Public Function GetLocalTime(UtcDate As Date) As Date
  1967. Return DateTime.SpecifyKind(UtcDate, DateTimeKind.Utc).ToLocalTime
  1968. End Function
  1969. ''' <summary>
  1970. ''' 打开网页。
  1971. ''' </summary>
  1972. Public Sub OpenWebsite(Url As String)
  1973. Try
  1974. Log("[System] 正在打开网页:" & Url)
  1975. Process.Start(Url)
  1976. Catch ex As Exception
  1977. Log(ex, "无法打开网页(" & Url & ")")
  1978. ClipboardSet(Url, False)
  1979. MyMsgBox("可能由于浏览器未正确配置,PCL2 无法为你打开网页。" & vbCrLf & "网址已经复制到剪贴板,若有需要可以手动粘贴访问。", "无法打开网页")
  1980. End Try
  1981. End Sub
  1982. ''' <summary>
  1983. ''' 打开 explorer。注意参数中的路径要尽量加上双引号!
  1984. ''' </summary>
  1985. Public Sub OpenExplorer(Argument As String)
  1986. Try
  1987. ShellOnly("explorer.exe", Argument)
  1988. Catch ex As Exception
  1989. Log(ex, "打开资源管理器失败,请尝试关闭安全软件(如 360 安全卫士)", LogLevel.Msgbox)
  1990. End Try
  1991. End Sub
  1992. ''' <summary>
  1993. ''' 设置剪贴板。将在另一线程运行,且不会抛出异常。
  1994. ''' </summary>
  1995. Public Sub ClipboardSet(Text As String, Optional ShowSuccessHint As Boolean = True)
  1996. RunInThread(Sub()
  1997. Dim RetryCount As Integer = 0
  1998. Retry:
  1999. Try
  2000. RunInUi(Sub()
  2001. My.Computer.Clipboard.Clear()
  2002. My.Computer.Clipboard.SetText(Text)
  2003. End Sub)
  2004. Catch ex As Exception
  2005. RetryCount += 1
  2006. If RetryCount <= 5 Then
  2007. Thread.Sleep(20)
  2008. GoTo Retry
  2009. Else
  2010. Log(ex, "可能由于剪贴板被其他程序占用,文本复制失败", LogLevel.Hint)
  2011. End If
  2012. End Try
  2013. If ShowSuccessHint Then Hint("已成功复制!", HintType.Finish)
  2014. End Sub)
  2015. End Sub
  2016. ''' <summary>
  2017. ''' 以 Byte() 形式获取程序中的资源。
  2018. ''' </summary>
  2019. Public Function GetResources(ResourceName As String) As Byte()
  2020. Log("[System] 获取资源:" & ResourceName)
  2021. Dim Raw As Byte() = My.Resources.ResourceManager.GetObject(ResourceName)
  2022. Return Raw
  2023. End Function
  2024. #End Region
  2025. #Region "UI"
  2026. '边距改变
  2027. ''' <summary>
  2028. ''' 相对增减控件的左边距。
  2029. ''' </summary>
  2030. Public Sub DeltaLeft(control As FrameworkElement, newValue As Double)
  2031. '安全性检查
  2032. DebugAssert(Not Double.IsNaN(newValue))
  2033. DebugAssert(Not Double.IsInfinity(newValue))
  2034. If TypeOf control Is Window Then
  2035. '窗口改变
  2036. CType(control, Window).Left += newValue
  2037. Else
  2038. '根据 HorizontalAlignment 改变数值
  2039. Select Case control.HorizontalAlignment
  2040. Case HorizontalAlignment.Left, HorizontalAlignment.Stretch
  2041. control.Margin = New Thickness(control.Margin.Left + newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2042. Case HorizontalAlignment.Right
  2043. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right - newValue, control.Margin.Bottom)
  2044. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2045. Case Else
  2046. DebugAssert(False)
  2047. End Select
  2048. End If
  2049. End Sub
  2050. ''' <summary>
  2051. ''' 设置控件的左边距。(仅针对置左控件)
  2052. ''' </summary>
  2053. Public Sub SetLeft(control As FrameworkElement, newValue As Double)
  2054. DebugAssert(control.HorizontalAlignment = HorizontalAlignment.Left)
  2055. control.Margin = New Thickness(newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2056. End Sub
  2057. ''' <summary>
  2058. ''' 相对增减控件的上边距。
  2059. ''' </summary>
  2060. Public Sub DeltaTop(control As FrameworkElement, newValue As Double)
  2061. '安全性检查
  2062. DebugAssert(Not Double.IsNaN(newValue))
  2063. DebugAssert(Not Double.IsInfinity(newValue))
  2064. If TypeOf control Is Window Then
  2065. '窗口改变
  2066. CType(control, Window).Top += newValue
  2067. Else
  2068. '根据 VerticalAlignment 改变数值
  2069. Select Case control.VerticalAlignment
  2070. Case VerticalAlignment.Top
  2071. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top + newValue, control.Margin.Right, control.Margin.Bottom)
  2072. Case VerticalAlignment.Bottom
  2073. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, control.Margin.Bottom - newValue)
  2074. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2075. Case Else
  2076. DebugAssert(False)
  2077. End Select
  2078. End If
  2079. 'If Double.IsNaN(newValue) OrElse Double.IsInfinity(newValue) Then Exit Sub '安全性检查
  2080. 'Select Case control.VerticalAlignment
  2081. ' Case VerticalAlignment.Top, VerticalAlignment.Stretch, VerticalAlignment.Center
  2082. ' control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2083. ' Case VerticalAlignment.Bottom
  2084. ' control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, -newValue)
  2085. ' 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, CType(control.Parent, Object).ActualHeight - control.ActualHeight - newValue)
  2086. 'End Select
  2087. End Sub
  2088. ''' <summary>
  2089. ''' 设置控件的顶边距。(仅针对置上控件)
  2090. ''' </summary>
  2091. Public Sub SetTop(control As FrameworkElement, newValue As Double)
  2092. DebugAssert(control.VerticalAlignment = VerticalAlignment.Top)
  2093. control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2094. End Sub
  2095. 'DPI 转换
  2096. Public ReadOnly DPI As Integer = System.Drawing.Graphics.FromHwnd(IntPtr.Zero).DpiX
  2097. ''' <summary>
  2098. ''' 将经过 DPI 缩放的 WPF 尺寸转化为实际的像素尺寸。
  2099. ''' </summary>
  2100. Public Function GetPixelSize(WPFSize As Double) As Double
  2101. Return WPFSize / 96 * DPI
  2102. End Function
  2103. ''' <summary>
  2104. ''' 将实际的像素尺寸转化为经过 DPI 缩放的 WPF 尺寸。
  2105. ''' </summary>
  2106. Public Function GetWPFSize(PixelSize As Double) As Double
  2107. Return PixelSize * 96 / DPI
  2108. End Function
  2109. 'UI 截图
  2110. ''' <summary>
  2111. ''' 将某个控件的呈现转换为图片。
  2112. ''' </summary>
  2113. Public Function ControlBrush(UI As FrameworkElement) As ImageBrush
  2114. Dim Width = UI.ActualWidth, Height = UI.ActualHeight
  2115. If Width < 1 OrElse Height < 1 Then Return New ImageBrush
  2116. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Pbgra32)
  2117. bmp.Render(UI)
  2118. Return New ImageBrush(bmp)
  2119. End Function
  2120. ''' <summary>
  2121. ''' 将某个控件的模拟呈现转换为图片。
  2122. ''' </summary>
  2123. Public Function ControlBrush(UI As FrameworkElement, Width As Double, Height As Double, Optional Left As Double = 0, Optional Top As Double = 0) As ImageBrush
  2124. UI.Measure(New Size(Width, Height))
  2125. UI.Arrange(New Rect(0, 0, Width, Height))
  2126. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Default)
  2127. bmp.Render(UI)
  2128. If Not (Left = 0 AndAlso Top = 0) Then UI.Arrange(New Rect(Left, Top, Width, Height))
  2129. Return New ImageBrush(bmp)
  2130. End Function
  2131. ''' <summary>
  2132. ''' 将 UI 内容固定为图片并进行 Clear。
  2133. ''' </summary>
  2134. Public Sub ControlFreeze(UI As Panel)
  2135. UI.Background = ControlBrush(UI)
  2136. UI.Children.Clear()
  2137. End Sub
  2138. ''' <summary>
  2139. ''' 将 UI 内容固定为图片并进行 Clear。
  2140. ''' </summary>
  2141. Public Sub ControlFreeze(UI As Border)
  2142. UI.Background = ControlBrush(UI)
  2143. UI.Child = Nothing
  2144. End Sub
  2145. ''' <summary>
  2146. ''' 将 XML 转换为对应 UI 对象。
  2147. ''' </summary>
  2148. Public Function GetObjectFromXML(Str As XElement)
  2149. Return GetObjectFromXML(Str.ToString)
  2150. End Function
  2151. ''' <summary>
  2152. ''' 将 XML 转换为对应 UI 对象。
  2153. ''' </summary>
  2154. Public Function GetObjectFromXML(Str As String)
  2155. Using Stream As New MemoryStream
  2156. Using Writer As New StreamWriter(Stream)
  2157. Writer.Write(Str)
  2158. Writer.Flush()
  2159. Stream.Position = 0
  2160. Return XamlReader.Load(Stream)
  2161. End Using
  2162. End Using
  2163. End Function
  2164. Private ReadOnly UiThreadId As Integer = Thread.CurrentThread.ManagedThreadId
  2165. ''' <summary>
  2166. ''' 当前线程是否为主线程。
  2167. ''' </summary>
  2168. Public Function RunInUi() As Boolean
  2169. Return Thread.CurrentThread.ManagedThreadId = UiThreadId
  2170. End Function
  2171. #End Region
  2172. #Region "Debug"
  2173. Public ModeDebug As Boolean = False
  2174. 'Log
  2175. Public Enum LogLevel
  2176. ''' <summary>
  2177. ''' 不提示,只记录日志。
  2178. ''' </summary>
  2179. Normal = 0
  2180. ''' <summary>
  2181. ''' 只提示开发者。
  2182. ''' </summary>
  2183. Developer = 1
  2184. ''' <summary>
  2185. ''' 只提示开发者与调试模式用户。
  2186. ''' </summary>
  2187. Debug = 2
  2188. ''' <summary>
  2189. ''' 弹出提示所有用户。
  2190. ''' </summary>
  2191. Hint = 3
  2192. ''' <summary>
  2193. ''' 弹窗,不要求反馈。
  2194. ''' </summary>
  2195. Msgbox = 4
  2196. ''' <summary>
  2197. ''' 弹窗,要求反馈。
  2198. ''' </summary>
  2199. Feedback = 5
  2200. ''' <summary>
  2201. ''' 弹窗,结束程序。
  2202. ''' </summary>
  2203. Assert = 6
  2204. End Enum
  2205. ''' <summary>
  2206. ''' 记录程序是否递交了错误提示,以确保运行测试正确。
  2207. ''' </summary>
  2208. Public IsErrorTriggered As Boolean = False
  2209. Private LogList As New StringBuilder
  2210. Private LogWritter As StreamWriter
  2211. Public Sub LogStart()
  2212. RunInNewThread(Sub()
  2213. Dim IsInitSuccess As Boolean = True
  2214. Try
  2215. For i = 4 To 1
  2216. If File.Exists(Path & "PCL\Log" & i & ".txt") Then
  2217. If File.Exists(Path & "PCL\Log" & (i + 1) & ".txt") Then File.Delete(Path & "PCL\Log" & (i + 1) & ".txt")
  2218. CopyFile(Path & "PCL\Log" & i & ".txt", Path & "PCL\Log" & (i + 1) & ".txt")
  2219. End If
  2220. Next
  2221. File.Create(Path & "PCL\Log1.txt").Dispose()
  2222. Catch ex As IOException
  2223. IsInitSuccess = False
  2224. Hint("可能同时开启了多个 PCL2,程序可能会出现未知问题!", HintType.Critical)
  2225. Log(ex, "日志初始化失败(疑似文件占用问题)")
  2226. Catch ex As Exception
  2227. IsInitSuccess = False
  2228. Log(ex, "日志初始化失败", LogLevel.Hint)
  2229. End Try
  2230. Try
  2231. LogWritter = New StreamWriter(Path & "PCL\Log1.txt", True) With {.AutoFlush = True}
  2232. Catch ex As Exception
  2233. LogWritter = Nothing
  2234. Log(ex, "日志写入失败", LogLevel.Hint)
  2235. End Try
  2236. While True
  2237. If IsInitSuccess Then
  2238. LogFlush()
  2239. Else
  2240. LogList = New StringBuilder '清空 LogList 避免内存爆炸
  2241. End If
  2242. Thread.Sleep(50)
  2243. End While
  2244. End Sub, "Log Writer", ThreadPriority.Lowest)
  2245. End Sub
  2246. Private ReadOnly LogFlushLock As New Object '防止外部调用 LogFlush 时同时输出多次日志
  2247. Public Sub LogFlush()
  2248. On Error Resume Next
  2249. If LogWritter Is Nothing Then Exit Sub
  2250. Dim Log As String = Nothing
  2251. SyncLock LogFlushLock
  2252. If LogList.Length > 0 Then
  2253. Dim LogListCache As StringBuilder
  2254. LogListCache = LogList
  2255. LogList = New StringBuilder
  2256. Log = LogListCache.ToString
  2257. End If
  2258. End SyncLock
  2259. If Log IsNot Nothing Then
  2260. LogWritter.Write(Log)
  2261. End If
  2262. End Sub
  2263. Private ReadOnly LogListLock As New Object '防止日志乱码,只在调试模式下启用
  2264. ''' <summary>
  2265. ''' 输出 Log。
  2266. ''' </summary>
  2267. ''' <param name="Title">如果要求弹窗,指定弹窗的标题。</param>
  2268. Public Sub Log(Text As String, Optional Level As LogLevel = LogLevel.Normal, Optional Title As String = "出现错误")
  2269. On Error Resume Next
  2270. '放在最后会导致无法显示极端错误下的弹窗(如无法写入日志文件)
  2271. '处理错误会导致再次调用 Log() 导致无限循环
  2272. '输出日志
  2273. Dim AppendText As String = "[" & GetTimeNow() & "] " & Text & vbCrLf '减轻同步锁占用
  2274. If ModeDebug Then
  2275. SyncLock LogListLock
  2276. LogList.Append(AppendText)
  2277. End SyncLock
  2278. Else
  2279. LogList.Append(AppendText)
  2280. End If
  2281. #If DEBUG Then
  2282. Console.Write(AppendText)
  2283. #End If
  2284. If IsProgramEnded OrElse Level = LogLevel.Normal Then Exit Sub
  2285. '去除前缀
  2286. Text = RegexReplace(Text, "", "\[[^\]]+?\] ")
  2287. '输出提示
  2288. Select Case Level
  2289. #If DEBUG Then
  2290. Case LogLevel.Developer
  2291. Hint("[开发者模式] " & Text, HintType.Info, False)
  2292. Case LogLevel.Debug
  2293. Hint("[调试模式] " & Text, HintType.Info, False)
  2294. #Else
  2295. Case LogLevel.Developer
  2296. Case LogLevel.Debug
  2297. If ModeDebug Then Hint("[调试模式] " & Text, HintType.Info, False)
  2298. #End If
  2299. Case LogLevel.Hint
  2300. IsErrorTriggered = True
  2301. Hint(Text, HintType.Critical, False)
  2302. Case LogLevel.Msgbox
  2303. IsErrorTriggered = True
  2304. MyMsgBox(Text, Title)
  2305. Case LogLevel.Feedback
  2306. IsErrorTriggered = True
  2307. If CanFeedback(False) Then
  2308. If MyMsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消") = 1 Then Feedback(False, True)
  2309. Else
  2310. MyMsgBox(Text & vbCrLf & vbCrLf & "将 PCL2 更新至最新版或许可以解决这个问题……", Title)
  2311. End If
  2312. Case LogLevel.Assert
  2313. IsErrorTriggered = True
  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. IsErrorTriggered = True
  2337. '获取错误信息
  2338. Dim ExFull As String = Desc & ":" & GetString(Ex, False)
  2339. '输出日志
  2340. Dim AppendText As String = "[" & GetTimeNow() & "] " & Desc & ":" & GetString(Ex, False, True) & vbCrLf '减轻同步锁占用
  2341. If ModeDebug Then
  2342. SyncLock LogListLock
  2343. LogList.Append(AppendText)
  2344. End SyncLock
  2345. Else
  2346. LogList.Append(AppendText)
  2347. End If
  2348. #If DEBUG Then
  2349. Console.Write(AppendText)
  2350. #End If
  2351. If IsProgramEnded Then Exit Sub
  2352. '输出提示
  2353. Select Case Level
  2354. Case LogLevel.Normal
  2355. #If DEBUG Then
  2356. Case LogLevel.Developer
  2357. Dim ExLine As String = Desc & ":" & GetString(Ex, True)
  2358. Hint("[开发者模式] " & ExLine, HintType.Info, False)
  2359. Case LogLevel.Debug
  2360. Dim ExLine As String = Desc & ":" & GetString(Ex, True)
  2361. Hint("[调试模式] " & ExLine, HintType.Info, False)
  2362. #Else
  2363. Case LogLevel.Developer
  2364. Case LogLevel.Debug
  2365. Dim ExLine As String = Desc & ":" & GetString(Ex, True)
  2366. If ModeDebug Then Hint("[调试模式] " & ExLine, HintType.Info, False)
  2367. #End If
  2368. Case LogLevel.Hint
  2369. Dim ExLine As String = Desc & ":" & GetString(Ex, True)
  2370. Hint(ExLine, HintType.Critical, False)
  2371. Case LogLevel.Msgbox
  2372. MyMsgBox(ExFull, Title)
  2373. Case LogLevel.Feedback
  2374. If CanFeedback(False) Then
  2375. If MyMsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消") = 1 Then Feedback(False, True)
  2376. Else
  2377. MyMsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL2 更新至最新版或许可以解决这个问题……", Title)
  2378. End If
  2379. Case LogLevel.Assert
  2380. Dim Time As Long = GetTimeTick()
  2381. If CanFeedback(False) Then
  2382. If MsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  2383. Else
  2384. MsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL2 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  2385. End If
  2386. If GetTimeTick() - Time < 1500 Then
  2387. '弹窗无法保留
  2388. Log("[System] PCL 已崩溃:" & vbCrLf & ExFull)
  2389. FormMain.EndProgramForce(Result.Exception)
  2390. Else
  2391. FormMain.EndProgramForce(Result.Fail)
  2392. End If
  2393. End Select
  2394. End Sub
  2395. '反馈
  2396. Public Sub Feedback(Optional ShowMsgbox As Boolean = True, Optional ForceOpenLog As Boolean = False)
  2397. On Error Resume Next
  2398. FeedbackInfo()
  2399. If ForceOpenLog OrElse (ShowMsgbox AndAlso MyMsgBox("若你在汇报一个 Bug,请点击 打开文件夹 按钮,并上传 Log(1~5).txt 中包含错误信息的文件。" & vbCrLf & "游戏崩溃一般与启动器无关,请不要因为游戏崩溃而提交反馈。", "反馈提交提醒", "打开文件夹", "不需要") = 1) Then
  2400. OpenExplorer("""" & Path & "PCL\""")
  2401. End If
  2402. OpenWebsite("https://github.com/Hex-Dragon/PCL2/issues/")
  2403. End Sub
  2404. Public Function CanFeedback(ShowHint As Boolean) As Boolean
  2405. If False.Equals(PageSetupSystem.IsLauncherNewest) Then
  2406. If ShowHint Then MyMsgBox("你的 PCL2 不是最新版,因此无法提交反馈。" & vbCrLf & "请先在 设置 → 启动器 中更新启动器,确认该问题在最新版中依然存在,然后再提交反馈。", "无法提交反馈")
  2407. Return False
  2408. Else
  2409. Return True
  2410. End If
  2411. End Function
  2412. ''' <summary>
  2413. ''' 在日志中输出系统诊断信息。
  2414. ''' </summary>
  2415. Public Sub FeedbackInfo()
  2416. On Error Resume Next
  2417. Log("[System] 诊断信息:" & vbCrLf &
  2418. "操作系统:" & My.Computer.Info.OSFullName & vbCrLf &
  2419. "剩余内存:" & Int(My.Computer.Info.AvailablePhysicalMemory / 1024 / 1024) & " M / " & Int(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024) & " M" & vbCrLf &
  2420. "DPI:" & DPI & "(" & Math.Round(DPI / 96, 2) * 100 & "%)" & vbCrLf &
  2421. "MC 文件夹:" & If(PathMcFolder, "Nothing") & vbCrLf &
  2422. "文件位置:" & Path)
  2423. End Sub
  2424. '断言
  2425. Public Sub DebugAssert(Exp As Boolean)
  2426. If Not Exp Then Throw New Exception("断言命中")
  2427. End Sub
  2428. '获取当前的堆栈信息
  2429. Public Function GetStackTrace() As String
  2430. Dim Stack As New StackTrace()
  2431. Return Join(Stack.GetFrames().Skip(1).Select(Function(f) f.GetMethod).
  2432. Select(Function(f) f.Name & "(" & Join(f.GetParameters.Select(Function(p) p.ToString).ToList, ", ") & ") - " & f.Module.ToString).ToList,
  2433. vbCrLf).Replace(vbCrLf & vbCrLf, vbCrLf)
  2434. End Function
  2435. #End Region
  2436. #Region "随机"
  2437. Private ReadOnly Random As New Random
  2438. ''' <summary>
  2439. ''' 随机选择其一。
  2440. ''' </summary>
  2441. Public Function RandomOne(Of T)(objects As ICollection(Of T)) As T
  2442. Return objects(RandomInteger(0, objects.Count - 1))
  2443. End Function
  2444. ''' <summary>
  2445. ''' 取随机整数。
  2446. ''' </summary>
  2447. Public Function RandomInteger(min As Integer, max As Integer) As Integer
  2448. Return Math.Floor((max - min + 1) * Random.NextDouble) + min
  2449. End Function
  2450. ''' <summary>
  2451. ''' 将数组随机打乱。
  2452. ''' </summary>
  2453. Public Function RandomChaos(Of T)(array As IList(Of T)) As IList(Of T)
  2454. RandomChaos = New List(Of T)
  2455. Do While array.Count > 0
  2456. Dim i As Integer = RandomInteger(0, array.Count - 1)
  2457. RandomChaos.Add(array(i))
  2458. array.RemoveAt(i)
  2459. Loop
  2460. End Function
  2461. #End Region
  2462. End Module